Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java and lookbehind in regex

Tags:

java

string

regex

I am trying to find a regex for the following:

All worlds matching @WORD@ exactly where WORD could be any word at all but are only after an = . I made the following:
(?<==)#.*?#) which works but only for patterns like =@SOMEWORD@ or @ANOTHERWORD@ but not for = @WORD@.
I am also interested in not being followed by = but could not figure out that.
Anyway using something like: (?<=\\s*=\\s*)#.*?#) but it does not work.
Any ideas?

Note: Strange but from here it says that variable length lookbehind is not supported in Java but this does not give me an exception

like image 771
Jim Avatar asked Nov 12 '22 18:11

Jim


1 Answers

If you are using look-behind, I'm assuming you are using Pattern and Matcher directly, to catch the words clean ("@WORD@" instead of "= @WORD@").

If that is indeed the case, all you need to do is add an optional white-space within the look-behind:

(?<==\\s?)@.*?@


Here is a test-code, returning "@WORD@":

Matcher m = Pattern.compile("(?<==\\s?)@.*?@").matcher("= @WORD@");
m.find();
System.out.println(m.group());
like image 136
XenoRo Avatar answered Nov 15 '22 11:11

XenoRo