正则表达式匹配某些东西,如果它前面没有其他东西 [英] Regex for matching something if it is not preceded by something else
本文介绍了正则表达式匹配某些东西,如果它前面没有其他东西的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 Java 中的正则表达式,我想编写一个正则表达式,当且仅当模式前面没有某些字符时才匹配.例如:
With regex in Java, I want to write a regex that will match if and only if the pattern is not preceded by certain characters. For example:
String s = "foobar barbar beachbar crowbar bar ";
如果 bar 前面没有 foo,我想匹配.所以输出将是:
I want to match if bar is not preceded by foo. So output would be:
barbar
beachbar
crowbar
bar
推荐答案
你想像这样使用 negative lookbehind
:
w*(?<!foo)bar
其中 (?<!x)
表示仅当它在此点之前没有x"时".
Where (?<!x)
means "only if it doesn't have "x" before this point".
有关详细信息,请参阅正则表达式 - 环视.
See Regular Expressions - Lookaround for more information.
编辑:添加了 w*
以捕获之前的字符(例如beach").
Edit: added the w*
to capture the characters before (e.g. "beach").
这篇关于正则表达式匹配某些东西,如果它前面没有其他东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文