0

我想将一些用户输入测试从 Java 移到 javascript。该代码假设在任何位置从用户输入字符串中删除通配符。我正在尝试将以下 Java 表示法转换为 javascript,但不断出现错误

"Invalid regular expression: /(?<!\")~[\\d\\.]*|\\?|\\*/: Invalid group".

我几乎没有使用正则表达式的经验。任何帮助将不胜感激:JAVA:

str = str.replaceAll("(?<!\")~[\\d\\.]*|\\?|\\*","");

我失败的javascript版本:

input = input.replace( /(?<!\")~[\\d\\.]*|\\?|\\*/g, '');    
4

1 回答 1

0

The problem, as anubhava points out, is that JavaScript doesn't support lookbehind assertions. Sad but true. The lookbehind assertion in your original regex is (?<!\"). Specifically, it's looking only for strings that don't start with a double quotation mark.

However, all is not lost. There are some tricks you can use to achieve the same result as a lookbehind. In this case, the lookbehind is there only to prevent the character prior to the tilde from being replaced as well. We can accomplish this in JavaScript by matching the character anyway, but then including it in the replacement:

input = input.replace( /([^"])~[\d.]*|\?|\*/g, '$1' );

Note that for the alternations \? and \*, there will be no groups, so $1 will evaluate to the empty string, so it doesn't hurt to include it in the replacement.

NOTE: this is not 100% equivalent to the original regular expression. In particular, lookaround assertions (like the lookbehind above) also prevent the input stream from being consumed, which can sometimes be very helpful when matching things that are right next to each other. However, in this case, I can't think of a way that that would be a problem. To make a completely equivalent regex would be more difficult, but I believe this meets the need of the original regex.

于 2013-11-12T18:34:58.100 回答