1

I'm trying to use JavaScript regular expression with the exec function and hoping to get matches for a group. I just can't figure out why I'm getting no matches.

Here is my code:

var elementClass="validate[required]"
var myRegexp = /validate\\[(*)\\]/g;
var match = myRegexp.exec(elementClass);

match is null every time. I can't figure out why. It should be getting "required".

Thanks for the help!

1
  • 1
    Java != JavaScript. I changed the title to reflect that. Commented Mar 3, 2013 at 0:13

2 Answers 2

3

Use this instead:

var myRegexp = /validate\[(.*)\]/;

First of all you only need one backslash to escape - otherwise you're searching for a literal backslash followed by the special meaning of what you were trying to escape.

Second, * just means "zero or more of the last thing", which in this case makes no sense because there is nothing there. . means "anything" (well, almost) so .* means "any number of anythings".

Finally, the g flag is unnecessary here, especially if you're trying to capture a part of the result.

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

2 Comments

Ok that works but one thing I'm noticing is I keep getting 2 results. So match has 2 elements. The first element is always just exactly what was put in, and the second is the part between the brackets, in this case required.
That's how regexes work. The first element of the match array is always the full match, then each subsequent entry corresponds to the next subpattern (in this case, the disabled string)
2

1) You have to many slashes

var myRegexp = /validate\[(.*?)\]/g;

2) If you want to match the part in square brackets only, you should use groups

var result = match[1];

7 Comments

Doesn't anyone bother testing their code before using it in an answer?
@Kolink can't check it right now, but don't see any reason for why it's null
Just hit F12, instant JavaScript console. See my answer for why yours won't work.
@Kolink for some reason either my nor your regex are working, should I downvote your too? gyazo.com/baeb57eb55676f6257222de3f83ef036
You are indeed correct. My apologies. I've become so accustomed to using String.match rather than RegExp.exec that I had forgotten how g works differently in the latter case. Downvote removed, upvote added.
|

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.