简体   繁体   中英

JavaScript Regular Expression Can't get a matched group

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!

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM