Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有以下正则表达式来匹配以“+”开头的文本的所有单词。
Pattern.compile("\\+[\\w-]+");
这很好用并且"+Foo or +Bar"匹配"+Foo"和"+Bar"。
"+Foo or +Bar"
"+Foo"
"+Bar"
如何扩展正则表达式以忽略以转义的 '+'-char 开头的单词?
"+Foo or +Bar but no \\+Hello"应该匹配"+Foo","+Bar" 但不"+Hello"匹配。
"+Foo or +Bar but no \\+Hello"
"+Hello"
(它应该适用于 JDK1.7。)
提前感谢您的帮助!
你可以尝试一个消极的lookbehind:
(?<!\\(\\{2})*)\+[\w-]+
通常,(?<!Y)X匹配X前面没有 a 的 a Y。
(?<!Y)X
X
Y
您可以使用负面的后视:
Pattern.compile("(?<!\\\\)\\+[\\w-]+");
Java支持有限长度的look-behind,所以这应该可以工作:
"(?<!\\\\)\\+[\\w-]+"
http://www.regular-expressions.info/lookaround.html