Search code examples
javascriptnashorn

Regex lookbehind/lookahead in Nashorn


Here is what i want to do: I want to replace certain tokens in a string, but only if they are not inside another word. Example:

  token= pos
  replacement= XXX
//Strings to check:
  Repository
  pos
  boss && pos
  boss && xpos && pos

//Expected results:
  Repository
  XXX
  boss && XXX
  boss && xpos && XXX

For that I created a regex:

/(?<!\w)POS(?!\w)/

The Problem is that POS should be a variable. Since this only works with the new Regexp Syntax i tried to modify it like this:

var rx = new RegExp("(?<!\\w)" + item[0] + "(?!\\w)");

As you might guessed, in the end there is a loop that should replace several tokens in a string (/g is not needed). The problem is, if I try to rund this codesegement above I always get an expection:

RuntimeException - org.mozilla.javascript.EcmaError: SyntaxError: Invalid quantifier ?

Now I'm not sure if the problem is a faulty regex or if it simply is a limitation of nashorn.


Solution

  • Assuming you want to replace pos only as a standalone word, just use word boundaries:

    var rx = new RegExp("\\b" + item[0] + "\\b");