Darthg8r
Darthg8r

Reputation: 12685

Regex not valid in JavaScript

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}$

Upvotes: 3

Views: 723

Answers (2)

Narendra Yadala
Narendra Yadala

Reputation: 9664

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

Upvotes: 4

FailedDev
FailedDev

Reputation: 26940

(?i)

Javascript does not support mode modifiers inside the regex.

Upvotes: 3

Related Questions