简体   繁体   English

Javascript正则表达式将文字括号分组吗?

[英]Javascript regex is grouping a literal parenthesis?

const str = `zell class="www-some" bro and class="ded_Me" or addClass('coolman') also addClass("boo-boo")`;

const allCssClassRegex = /addClass\(["|']([a-zA-Z0-9-_]+)["|']\)|class=["|']([a-zA-Z0-9-_]+)["|']/gi;
let match;

while ((match = allCssClassRegex.exec(str)) != null) {
    console.log(match);
}

I'm trying to match two patterns and have the second member of the array be the match. 我正在尝试匹配两个模式,并使数组的第二个成员成为匹配项。 The output looks like: 输出如下:

[ 'class="www-some"',
  undefined,
  'www-some',
  index: 5,
  input: 'zell class="www-some" bro and class="ded_Me" or addClass(\'coolman\') also addClass("boo-boo")' ]
[ 'class="ded_Me"',
  undefined,
  'ded_Me',
  index: 30,
  input: 'zell class="www-some" bro and class="ded_Me" or addClass(\'coolman\') also addClass("boo-boo")' ]
[ 'addClass(\'coolman\')',
  'coolman',
  undefined,
  index: 48,
  input: 'zell class="www-some" bro and class="ded_Me" or addClass(\'coolman\') also addClass("boo-boo")' ]
[ 'addClass("boo-boo")',
  'boo-boo',
  undefined,
  index: 73,
  input: 'zell class="www-some" bro and class="ded_Me" or addClass(\'coolman\') also addClass("boo-boo")' ]

It appears that the literal ( it somehow being interpreted as a group because it the second member of match is undefined (and 1, 2 slots are matches). 似乎字面量(它以某种方式被解释为一个组,因为它是match的第二个成员未定义(并且1,2个槽位是匹配项)。

How do I go about fixing this regex to have the second array slot be the match only? 我该如何解决此正则表达式使第二个数组插槽仅匹配?

You have a few issues with your pattern, and it can probably be condensed somewhat: 您的模式有一些问题,它可能在某种程度上可以概括为:

/(?:addClass[(]*|class=)["']([a-zA-Z0-9_-]+)["'][)]*/gi;

Also inside a character class [9-_] implies 9 through _ , which you probably don't want. 同样,在字符类[9-_]包含9 _ ,您可能不需要。 If you rearrange the characters so that it's like [9_-] (where the "-") is at the end then it will work. 如果重新排列字符,使其像[9_-] (其中的“-”)在末尾,则它将起作用。

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

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