【问题标题】:How to replace every second occurrence of a word in a string如何替换字符串中每出现一次的单词
【发布时间】:2015-04-27 04:22:57
【问题描述】:

我有以下问题需要在 PowerShell 中解决 - 如何替换大字符串中每出现一次的字符串?

例子:

ReplaceEverySecond "AAAABAAAAAABAAAABAAABAA" "B" "x"

会变成:

“AAAAxAAAAAAAAAAAAxAAAA”

我怀疑最简单的方法是构造正则表达式并使用 -replace 函数,但我不知道如何构造表达式。

感谢大家的帮助。

【问题讨论】:

  • 我认为您要替换的字符串长度可能超过一个字符?
  • 是的!抱歉,我没有说清楚。
  • 在您的示例中,您更改了“B”的第一次出现而不是第二次出现..

标签: .net regex powershell


【解决方案1】:

假设"BA" 是要替换的字符串。然后你可以使用正则表达式

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

并替换为\1xx\2。这不仅限于文字字符串,您还可以使用正则表达式代替 BA

测试它live on regex101.com

说明:

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

【讨论】:

  • powershell 示例:"fffbaffffbaffffbaffffbafff" -replace '(BA(?:(?!BA).)*)BA((?:(?!BA).)*)', '$1xx$2'
猜你喜欢
  • 2020-06-08
  • 2022-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多