5

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

Community
  • 1
  • 1
Jim
  • 18,826
  • 34
  • 135
  • 254

2 Answers2

1

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());
CosmicGiant
  • 6,275
  • 5
  • 43
  • 58
0

This pattern matches an equals, followed by an optional space and a word encased in @ symbols:

Pattern pattern = Pattern.compile("= ?@(.*)@");
Matcher matcher = pattern.matcher("=@WORD@");
if (matcher.matches()) {
  System.out.println(matcher.group(1));
}

// Prints: "WORD"

Can't see a need for a lookbehind, unless I've misunderstood the task you wish to accomplish. However, the following should work:

Pattern pattern = Pattern.compile("(?<== ?)@(.*)@");
Matcher matcher = pattern.matcher("= @WORD@");
if (matcher.find()) {
  System.out.println(matcher.group(1));
}

// Prints: "WORD"

The negative pattern is then accomplished as follows:

Pattern pattern = Pattern.compile("(?<!= ?)@(.*)@");
Matcher matcher = pattern.matcher("=@WORD@");
System.out.println(matcher.find());

// Prints: "false"
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254