How to ignore escaped character in regex?

I have the following regular expression to match all words of a text starting with "+".

Pattern.compile("\\+[\\w-]+"); 

This works well and matches "+Foo or +Bar" - "+Foo" and "+Bar" .

How to extend a regular expression to ignore words starting with an escaped "+" - char?

"+Foo or +Bar but no \\+Hello" should match "+Foo" and "+Bar" , but not "+Hello" .

(It should work for JDK1.7.)

Thanks in advance for your help!

+8
java regex
source share
3 answers

You can try negative lookbehind :

 (?<!\\(\\{2})*)\+[\w-]+ 

In the general case (?<!Y)X corresponds to X , which is not preceded by Y

+13
source share

You can use a negative look:

 Pattern.compile("(?<!\\\\)\\+[\\w-]+"); 
+4
source share

Java supports finite-length looks, so this should work:

 "(?<!\\\\)\\+[\\w-]+" 

http://www.regular-expressions.info/lookaround.html

+3
source share

All Articles