1

I want to move some user input test from Java to javascript. The code suppose to remove wildcard characters out of user input string, at any position. I'm attempting to convert the following Java notation to javascript, but keep getting error

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

I have almost no experience with regex expressions. Any help will be much appreciated: JAVA:

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

My failing javascript version:

input = input.replace( /(?<!\")~[\\d\\.]*|\\?|\\*/g, '');    
3
  • 4
    There is no lookbehind in Javascript. Commented Nov 12, 2013 at 18:13
  • 1
    Can someone confirm that in JS \d also needs to be written as \\d like in Java? Commented Nov 12, 2013 at 18:17
  • 1
    @Pshemo There is no need to escape \ as \\ when writing a literal regexp like above. Commented Nov 12, 2013 at 18:22

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is awesome! I didn't know where to start. This match is close enough for me, and I'm definitely using it. Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.