Javascript RegExp非捕获组 [英] Javascript RegExp non-capturing groups
本文介绍了Javascript RegExp非捕获组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一套RegExps,以将CSS选择器转换为ID和类的数组。
I am writing a set of RegExps to translate a CSS selector into arrays of ids and classes.
例如,我希望将#foo#bar返回['foo','bar']。
For example, I would like '#foo#bar' to return ['foo', 'bar'].
我一直在尝试使用
"#foo#bar".match(/((?:#)[a-zA-Z0-9\-_]*)/g)
,但是当非捕获前缀?:忽略#字符时,它将返回['#foo','#bar']。
but it returns ['#foo', '#bar'], when the non-capturing prefix ?: should ignore the # character.
有没有比切片每个返回的字符串更好的解决方案了?
Is there a better solution than slicing each one of the returned strings?
推荐答案
您可以在循环中使用 .replace()
或 .exec()
来构建数组。
You could use .replace()
or .exec()
in a loop to build an Array.
使用 .replace()
:
var arr = [];
"#foo#bar".replace(/#([a-zA-Z0-9\-_]*)/g, function(s, g1) {
arr.push(g1);
});
使用 .exec( )
:
var arr = [],
s = "#foo#bar",
re = /#([a-zA-Z0-9\-_]*)/g,
item;
while (item = re.exec(s))
arr.push(item[1]);
这篇关于Javascript RegExp非捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文