我想知道如何使用regexp来匹配某个特定匹配之后的短语。比如:
var phrase = "yesthisismyphrase=thisiswhatIwantmatched";
var match = /phrase=.*/;
这将从phrase=
匹配到字符串的末尾,但是可以在之后获取所有内容,而不必修改字符串。
发布于 2010-12-31 10:00:38
您使用capture groups (用括号表示)。
通过match或exec函数执行regex时,返回一个由捕获组捕获的子字符串组成的数组。然后,您可以访问通过该数组捕获的内容。例如:
var phrase = "yesthisismyphrase=thisiswhatIwantmatched";
var myRegexp = /phrase=(.*)/;
var match = myRegexp.exec(phrase);
alert(match[1]);
或
var arr = phrase.match(/phrase=(.*)/);
if (arr != null) { // Did it match?
alert(arr[1]);
}
发布于 2010-12-31 09:55:36
phrase.match(/phrase=(.*)/)[1]
返回
"thisiswhatIwantmatched"
括号指定一个所谓的捕获组。捕获组的内容被放入结果数组中,从1开始(0是整个匹配)。
发布于 2018-05-13 22:21:52
这并不难,只要假设你的背景是:
const context = "https://example.com/pa/GIx89GdmkABJEAAA+AAAA";
我们希望在pa/
之后有一个模式,所以使用下面的代码:
const pattern = context.match(/pa\/(.*)/)[1];
第一项包括pa/
,但是对于分组的第二项没有pa/
,您可以使用所需的每一项。
https://stackoverflow.com/questions/4571531
复制相似问题