Powershell - 如何将使用正则表达式找到的字符串大写 [英] Powershell - How to UpperCase a string found with a Regex

查看:49
本文介绍了Powershell - 如何将使用正则表达式找到的字符串大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 powershell 脚本来解析 HTM 文件.我需要找到文件中的所有链接文件,然后将文件路径、文件名和扩展名大写.(可以是任何文件中的 30 或 40 个链接).我遇到问题的部分是下面 -replace staement 的第二部分(XXXX"部分).正则表达式将找到我正在寻找的字符串,但我无法弄清楚如何用大写版本替换"该字符串,然后使用新链接更新现有文件.

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";

在现有文件中更新的最终字符串应如下所示 HREF="FILEPATH/FILE.HTM"

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

推荐答案

beatcracker 和 briantist 都推荐你参考这个答案,这显示了正确的方法.正则表达式无法转换为大写,因此您需要挂钩到 .NET String.ToUpper() 函数.

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.

不要使用 -replace,而是在 $regex 对象上使用 .Replace() 方法(如另一个答案中所述).您还需要 ForEach-Object 构造,以便为管道中的每个字符串调用它.为了便于阅读,我将最后一行分开,但如果需要,您可以将其保留在一行上.

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"

这篇关于Powershell - 如何将使用正则表达式找到的字符串大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆