Javascript-仅获取正则表达式匹配项的可变部分 [英] Javascript -- get only the variable part of a regex match
本文介绍了Javascript-仅获取正则表达式匹配项的可变部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定:
var regexp = new RegExp("<~~include(.*?)~~>", "g");
在javascript中将变量分配给.*匹配的变量的简便方法是什么?
What's the easist way in javascript to assign a variable to whatever's matched by .*?
我可以做到,但这有点丑陋:
I can do this, but it's a little ugly:
myString.match(regexp).replace("<~~include", "").replace("~~>", "");
推荐答案
Javascript应该在正则表达式匹配项上返回一个数组对象,其中数组的零索引是匹配的整个字符串,而以下索引是捕获组.在您的情况下,例如:
Javascript should return an array object on a regex match, where the zero index of the array is the whole string that was matched and the following indexes are the capture groups. In your case something like:
var myVar = regexp.exec(myString)[1];
应将(.*?)
捕获组的值分配给 myVar
.
should assign the value of the (.*?)
capture group to myVar
.
这篇关于Javascript-仅获取正则表达式匹配项的可变部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文