View Full Version : Getting muddled with RegExp

09-01-2008, 01:57 PM
Hi, I'm really new to Javascript and am trying to work my way through someone else's code.. But I'm getting really lost with all the brackets and backslashes involved in this RegExp.

var rtRegexRequired = new RegExp ("(\\(Required\\))","gi");

I just need to know what this RegExp is looking for..


Philip M
09-01-2008, 03:33 PM
Are you sure that it is not:-

var rtRegexRequired = new RegExp ("\(\(Required\)\)","gi");

If so the regex is looking for

((Required)) global match and case insensitive.
The backslashes \ are escape characters so that the ( and ) are interpreted as literals.

Label on Sainsbury's peanuts -- "Warning: contains nuts."

09-02-2008, 12:39 AM
Are you sure that it is not:-

Yeah, see I think thats where I'm getting confused, I expected it to be looking for ((Required)), but its really not.. Wonder if the original coder just made a typo..

That is exactly the code in the js, so as it is, what's it looking for?

09-02-2008, 03:18 AM
Okay, let's try explaining then: Have a look at the structure of it:

new RegExp ("(\\(Required\\))","gi");
Okay, so "(\\(Required\\))" is a string literal, right? That means the reverse solidi (a.k.a. backslashes) are string escapes, and you need to perform the escaping to know what the actual pattern looks like.
So, the actual pattern looks like this: (\(Required\)) (where the reverse solidi are regex escapes), and the code indeed could just as well have been written as
var rtRegexRequired = /(\(Required\))/gi;

What does that pattern do, then? Well, its matching for a string that looks like this: "(Required)" case insensitively. The entire string it matches is enclosed in a capturing group, however, so the string will be captured. And finally, the pattern has a global flag on it, which will affect the behaviour of re.exec, str.match and str.replace.