Reputation: 28
I have a question regarding regular expressions in nodejs/javascript.
What I am trying to achieve is to convert a regex (loaded from a database as a string) without any escaping to a RegExp object in js.
var regex = /Apache\/([0-9\.]+) \(([a-zA-Z ]+)\) (.+)/;
var regexString = '/Apache\/([0-9\.]+) \(([a-zA-Z ]+)\) (.+)/';
var str = 'Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny18';
var match = str.match(regex);
var match2 = str.match(new RegExp(regexString));
console.log(match);
console.log(match2);
That's what I tried so far. But as you can see it won't match if the string gets escaped... My output:
[ 'Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny18',
'2.2.9',
'Debian',
'PHP/5.2.6-1+lenny18',
index: 0,
input: 'Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny18' ]
null
Am I missing something simple? If not any suggestions for me? Thanks
Upvotes: 0
Views: 301
Reputation: 350760
The two bounding /
are not supposed to be present when used in the string argument of new RegExp()
.
Also, when you would write the string as a literal (which I understand is not really your case, since you get the string from the DB), you need to escape any backslashes in that literal to \\
:
var regex = /Apache\/([0-9\.]+) \(([a-zA-Z ]+)\) (.+)/;
var regexString = 'Apache\/([0-9\.]+) \\(([a-zA-Z ]+)\\) (.+)';
var str = 'Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny18';
var match = str.match(regex);
var match2 = str.match(new RegExp(regexString));
console.log(match);
console.log(match2);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 2