如何修改PowerShell正则,仅替换引号后:/前的目标文本?
正则表达式替换问题及解决方案
问题描述
我有一个文本文件content.txt,内容如下:
Some other text 1 "one" : "Text To Replace1:/Text To Stay.133" Some other text 2 "five" : "Text To Change2:/Another Text To Stay.50" Some other text 5
编写的PowerShell脚本如下:
$SRCFile = "K:\content.txt" $DSTFile = "K:\result.txt" $Text2Replace = "YabaDaba.du:/" Get-Content $SRCFile | ForEach-Object { $_ -replace ".*:\/", $Text2Replace } | Out-File $DSTFile
脚本能运行,但会选中:/左侧的整行内容。需求是仅替换前一个引号(不含引号)到:/之间的文本。
解决方案
使用带正向先行断言的非贪婪正则表达式即可实现精准匹配,替换规则如下:
正则表达式
(?<=")[^"]*?:\/
规则说明:
(?<="):正向先行断言,匹配双引号但不捕获,确保从引号后开始匹配[^"]*?:非贪婪匹配任意非引号字符,避免过度匹配整行或其他引号内容:/:精准定位目标分隔符
修改后的脚本
$SRCFile = "K:\content.txt" $DSTFile = "K:\result.txt" $Text2Replace = "YabaDaba.du:/" Get-Content $SRCFile | ForEach-Object { $_ -replace '(?<=")[^"]*?:\/', $Text2Replace } | Out-File $DSTFile
最终效果
处理后result.txt的内容为:
Some other text 1 "one" : "YabaDaba.du:/Text To Stay.133" Some other text 2 "five" : "YabaDaba.du:/Another Text To Stay.50" Some other text 5
内容的提问来源于stack exchange,提问作者KolesGit
相关产品推荐
相关产品推荐

