匹配多个值
问题描述:
我有一个像这样的字符串:匹配多个值
str = 'autocomplete=\\\"off\\\" name=\\\"composer_session_id\\\" value=\\\"1557423901\\\" \\\/>\\u003cinput type=\\\"hidden\\\" autocomplete=\\\"off\\\" name=\\\"is_explicit_place\\\" id=\\\"u436754_5\\\"';
和正则表达式匹配:
str.match(/(composer_session_id|is_explicit_place)\\" (?:value|id)=\\"([_a-zA-Z0-9]+)\\"/g)
它的工作(有点'),但尽管事实上,我使用的是捕获群体得到(composer_session_id|is_explicit_place)
和([_a-zA-Z0-9]+)
结果数组只包含两个元素(最大匹配字符串):
["composer_session_id\" value=\"1557423901\"", "is_explicit_place\" id=\"u436754_5\""]
我在这里错过了什么?
如何在一次运行中使用regexp获取字符串:composer_session_id,is_explicit_place,1557423901和u436754_5?
加分要解释为什么只有两个字符串返回和解决方案获取值我需要的不涉及使用split()
和/或replace()
。
答
如果正则表达式与g标志一起使用,方法string.match只返回匹配的数组,它不包含捕获的组。方法RegExp.exec返回最后一次匹配的数组和最后匹配的捕获组,这也不是解决方案。 要实现你在一个比较简单的方法,我建议寻找到替代品的功能所需要的:
<script type="text/javascript">
var result = []
//match - the match
//group1, group2 and so on - are parameters that contain captured groups
//number of parameters "group" should be exactly as the number of captured groups
//offset - the index of the match
//target - the target string itself
function replacer(match, group1, group2, offset, target)
{
if (group1 != "")
{
//here group1, group2 should contain values of captured groups
result.push(group1);
result.push(group2);
}
//if we return the match
//the target string will not be modified
return match;
}
var str = 'autocomplete=\\\"off\\\" name=\\\"composer_session_id\\\" value=\\\"1557423901\\\" \\\/>\\u003cinput type=\\\"hidden\\\" autocomplete=\\\"off\\\" name=\\\"is_explicit_place\\\" id=\\\"u436754_5\\\"';
//"g" causes the replacer function
//to be called for each symbol of target string
//that is why if (group1 != "") is needed above
var regexp = /(composer_session_id|is_explicit_place)\\" (?:value|id)=\\"([_a-zA-Z0-9]+)\\"/g;
str.replace(regexp, replacer);
document.write(result);
</script>
你知道你可以嵌套捕获组? –
是的,我知道 - 这对我有帮助吗? – WTK
你可以给未经转义的原始字符串和正则表达式吗? – pastacool