我已经放弃了自己解决这个问题。
用于正则表达式的示例字符串:
"this","is","a","test"
下面的正则表达式适用于双引号(一次)和无引号文本。
[`""`]?is[`""`]?
然而,它匹配的部分字符串如下 is 在里面 this ,在示例字符串中。
is
this
希望执行以下操作,例如删除 "is" 或 是 在示例字符串中
"is"
是
$String = '"this`","is","a","test' $ConstructedRegex = "[`""`]?is[`""`]?,?" $String.replace($ConstructedRegex,"").trimstart(",").trimend(",")
预期成果: $String = "this","a","test"
$String = "this","a","test"
首先要考虑的是 .Replace 是用于文字替换的字符串方法,它不适用于正则表达式。你想用的是 -replace ,用于替换的正则表达式运算符。
.Replace
-replace
至于你如何处理这个问题,因为 is 可以引用也可以不引用,它可以在任何地方,包括字符串的开头或结尾,可能最简单的方法是拆分 , 然后过滤令牌不匹配的地方 ^"?is"?$ ( -notmatch 与其他比较运算符一样,当左侧有一个集合时,它可以充当过滤器),最后用 , :
,
^"?is"?$
-notmatch
'is,"this","is","a","test",is' -split ',' -notmatch '^"?is"?$' -join ',' # Outputs: "this","a","test"
如果你想通过替换来做到这一点,你也许可以使用这种模式,但我看不到一次完成的方法(它需要一个 TrimEnd ):
TrimEnd
$result = 'is,"this","is","a","test",is' -replace '(?<=(?:^|,))"?is"?(?:,|$)' $result.TrimEnd(',')