3

This regex isn't valid in JavaScript. It says there is an invalid group. Can someone help me make it work?

(?i)^(?![\. -])(?!.*[\. -]$)[\w!$%'*+/=?^`{|\.}~ -]{1,64}$

2 Answers 2

4

Update: Updating as per suggestions given in comments.

Use one of these three expressions instead. It is the same regex, just fixing the (?i) part and adding required escaping to match Javascript specifications.

var regex = new RegExp("^(?![\\. -])(?!.*[\\. -]$)[\\w!$%'*+/=?^`{|\\.}~ -]{1,64}$", "i");
var regex = new RegExp('^(?![\\. -])(?!.*[\\. -]$)[\\w!$%\'*+/=?^`{|\\.}~ -]{1,64}$', "i");
var regex =  /^(?![\. -])(?!.*[\. -]$)[\w!$%'*+/=?^`{|\.}~ -]{1,64}$/i;

If you are using new RegExp to construct your regex object, then you have to escape all your backslashes. The difference between first and second expression is that the second one is using single quotes to construct the regex string and there is a single quote as part of your regex, so you have to escape the single quote to make it work properly. The third expression uses the /pattern/flags syntax to construct the regex object. As pointed by Mike in comments, you have to escape / if it is not inside a character set. All your /s are inside character sets, so no escaping is necessary.

Check out more on javascript regex syntax here https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp

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

7 Comments

The non-escaped forward slash is not a problem for Darthg8r: something like new RegExp('a/b') is perfectly valid. /a/b/ would not be valid, but Darthg8r would not be getting to the "invalid group" error message if (s)he were doing that.
Sure. I just want to make sure OP is aware of that. If he is using new RegExp then he has to escape `\` symbols. I am not sure about the context in which OP is using his regex.
The / is not a problem because it is inside a character group. /[/]/ is a perfectly valid regular expression literal. 15.10.1 defines ClassAtomNoDash :: SourceCharacter but not one of \ or ] or - | \ ClassEscape
@Mike Samuel - No, the / must be escaped everywhere, even inside a char class when the regex is specified using the JavaScript: /regex/flags literal regex syntax. The / is the regex delimiter.
@ridgerunner. Try it. /[/]/ will work in any major interpreter. The delimiter for a character group is ], not / which is why ClassAtomNoDash excludes ] but includes /.
|
3
(?i)

Javascript does not support mode modifiers inside the regex.

Comments

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.