[英]How to replace every second occurrence of a word in a string
我在PowerShell中需要解决以下问题-如何替换大字符串中第二次出现的字符串?
例:
ReplaceEverySecond "AAAABAAAAAABAAAABAAABAA" "B" "x"
会成为:
“ AAAAxAAAAAABAAAAxAAABAA”
我怀疑最简单的方法是构造一个正则表达式并使用-replace函数,但是我不知道如何构造该表达式。
感谢大家的帮助。
让我们假设"BA"
为要替换的字符串。 然后你可以使用正则表达式
(BA(?:(?!BA).)*)BA((?:(?!BA).)*)
并替换为\\1xx\\2
。 这不仅限于文字字符串,还可以使用正则表达式代替BA
。
说明:
( # Start group 1
BA # Match BA (no. 1)
(?: # Match in non-capturing group:
(?!BA) # (unless it's at the start of "BA")
. # any character
)* # any number of times.
) # End of group 1
BA # Match BA (no. 2)
((?:(?!BA).)*) # and anything that follows until the next BA, if present.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.