[英]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.