0

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

0

1 Answer 1

2

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

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

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.