简体   繁体   English

如何替换字符串中单词的第二次出现

[英]How to replace every second occurrence of a word in a string

I have a following problem to be solved in PowerShell - how do I replace every second occurrence of a string in a large string? 我在PowerShell中需要解决以下问题-如何替换大字符串中第二次出现的字符串?

Example: 例:

ReplaceEverySecond "AAAABAAAAAABAAAABAAABAA" "B" "x"

would become: 会成为:

"AAAAxAAAAAABAAAAxAAABAA" “ AAAAxAAAAAABAAAAxAAABAA”

I suspect the easiest would to construct a regular expression and to use the -replace function, but I cannot figure out how to construct the expression. 我怀疑最简单的方法是构造一个正则表达式并使用-replace函数,但是我不知道如何构造该表达式。

Thanks to all for your help. 感谢大家的帮助。

Let's assume "BA" as the string to be replaced. 让我们假设"BA"为要替换的字符串。 Then you could use the regex 然后你可以使用正则表达式

(BA(?:(?!BA).)*)BA((?:(?!BA).)*)

and replace with \\1xx\\2 . 并替换为\\1xx\\2 This isn't limited to literal strings, you could also use a regex in place of BA . 这不仅限于文字字符串,还可以使用正则表达式代替BA

Test it live on regex101.com . 在regex101.com上进行实时测试。

Explanation: 说明:

(              # 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM