Powershell - How to UpperCase a string found with a Regex [duplicate]

泪湿孤枕 提交于 2021-02-04 19:50:06

问题


I am writing a powershell script to parse the HTM file. I need to find all the links file in the file and then uppercase the filepath, filename and extention. (could be 30 or 40 links in any file). The part I'm having trouble with is the 2nd part of the -replace staement below (the 'XXXX' part). The regex WILL find the strings I'm looking for but I can't figure out how to 'replace' that string with a uppercase version, then update the existing file with a new links.

I hope I'm explaining this correctly. Appreciate any assistance that anyone can provide.

This is the code I have so far...

$FilePath = 'C:\WebDev'
$FileName = 'Class.htm'
[regex]$regex='(href="[^.]+\.htm")'
#Will Match the string  href="filepath/file.htm"

(  Get-Content "$FilePath\$FileName")  -replace $regex ,  'XXXX' | Set-Content "$FilePath\$FileName";

Final string that gets updated in the existing file should look like this HREF="FILEPATH/FILE.HTM"


回答1:


Both beatcracker and briantist refer you to this answer, which shows the correct approach. Regex expressions cannot convert to uppercase, so you need to hook into the .NET String.ToUpper() function.

Instead of using -replace, use the .Replace() method on your $regex object (as described in the other answer). You also need the ForEach-Object construct so it gets called for each string in the pipeline. I've split up the last line for readability, but you can keep it on one line if you must.

$FilePath = 'C:\WebDev'
$FileName = 'Class.htm'
[regex]$regex='(href="[^.]+\.htm")'

(Get-Content "$FilePath\$FileName") |
   ForEach-Object { $regex.Replace($_, {$args[0].Value.ToUpper()}) } |
   Set-Content "$FilePath\$FileName"


来源:https://stackoverflow.com/questions/37604295/powershell-how-to-uppercase-a-string-found-with-a-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!