[英]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.问题是 POS 应该是一个变量。 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).正如您可能猜到的那样,最后有一个循环应该替换字符串中的多个标记(不需要 /g)。 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.现在我不确定问题是错误的正则表达式还是仅仅是 nashorn 的限制。
Assuming you want to replace pos
only as a standalone word, just use word boundaries:假设您只想将
pos
替换为独立单词,只需使用单词边界:
var rx = new RegExp("\\b" + item[0] + "\\b");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.