You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 19:50:24