简体   繁体   English

RegEx在第一次出现后匹配所有出现的字符*?

[英]RegEx to match all occurrences of a character *after* the first occurrence?

For instance if I am trying to match 'w's in the input string 例如,如果我想在输入字符串中匹配'w'

edward woodward 爱德华伍德沃德

the two 'w's in the second word should be matched, not the one in the first word. 第二个单词中的两个'w'应该匹配,而不是第一个单词中的那个。

I have an inkling the solution might involve 'negative lookbehind' but just can't get any working solution. 我有一个问题,解决方案可能涉及'负面看待',但是无法获得任何有效的解决方案。

(I am working with Objective C and the regex replace methods on NSMutableString but I would also be happy to hear about solutions for any regex implementation.) (我正在使用Objective C和NSMutableString上的正则表达式替换方法,但我也很高兴听到任何正则表达式实现的解决方案。)

Your problem is that you'd need not just lookbehind (which some regex flavors don't support at all) but infinite repetition inside the lookbehind assertion (which only very few flavors support, like .NET for example). 你的问题是你不仅需要看后面(一些正则表达式根本不支持),而是在lookbehind断言中进行无限重复(例如,只有非常少的口味支持,例如.NET)。

Therefore, the .NET- or JGSoft-compatible regex 因此,.NET-或JGSoft兼容的正则表达式

(?<=w.*)w

won't work in Objective C, Python, Java, etc. 不适用于Objective C,Python,Java等。

So you need to do it in several steps: First find the string after the first w : 所以你需要分几步完成:首先在第一个w之后找到字符串:

(?<=w).*

(if you have lookbehind support at all), then take the match and search for w inside that. (如果你有背后的支持),那么拿下比赛并在里面搜索w

If lookbehind isn't supported, then search for w(.*) and apply the following search to the contents of the capturing group 1 ( $1 ). 如果不支持lookbehind,则搜索w(.*)并将以下搜索应用于捕获组1( $1 )的内容。

To replace every N -th "w" (where N > 1 ) with an "X" for example, you could search for the pattern: 要用"X"替换每个第N"w" (其中N > 1 ),您可以搜索模式:

(?<=w)(.*?)w

and replace it with: 并替换为:

$1X

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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