Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore escaped character in regex?

Tags:

java

regex

I have the following regex to match all words of a text starting with '+'.

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

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

How can I extend the regex to ignore words starting with an escaped '+'-char?

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

(It should work for JDK1.7.)

Thanks in advance for any help!

like image 304
t777 Avatar asked Jul 20 '13 22:07

t777


3 Answers

You could try a negative lookbehind:

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

In general, (?<!Y)X matches an X that is not preceded by a Y.

like image 184
arshajii Avatar answered Nov 15 '22 15:11

arshajii


Java supports finite-length look-behind, so this should work:

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

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

like image 26
Chip Camden Avatar answered Nov 15 '22 16:11

Chip Camden


You can use negative look-behind:

Pattern.compile("(?<!\\\\)\\+[\\w-]+");
like image 4
Rohit Jain Avatar answered Nov 15 '22 15:11

Rohit Jain