简体   繁体   中英

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?

Example:

ReplaceEverySecond "AAAABAAAAAABAAAABAAABAA" "B" "x"

would become:

"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.

Thanks to all for your help.

Let's assume "BA" as the string to be replaced. Then you could use the regex

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

and replace with \\1xx\\2 . This isn't limited to literal strings, you could also use a regex in place of BA .

Test it live on 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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