简体   繁体   English

JavaScript正则表达式无法获取匹配的组

[英]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. 我正在尝试将javascript正则表达式与exec函数一起使用,并希望获取组的匹配项。 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. 每次匹配都为null。 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. 最后,这里g标志是不必要的,尤其是当您尝试捕获部分结果时。

1) You have to many slashes 1)你必须很多斜线

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

2) If you want to match the part in square brackets only, you should use groups 2)如果只想匹配方括号中的部分,则应使用组

var result = match[1];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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