我想知道如何使用正则表达式匹配某个匹配后的短语。像:
var phrase = "yesthisismyphrase=thisiswhatIwantmatched";
var match = /phrase=.*/;
这将匹配从phrase=
到字符串的结尾,但是否可以在phrase=
之后获取所有内容而无需修改字符串?
答案 0 :(得分:53)
您使用capture groups(用括号表示)。
当您通过match或exec函数执行正则表达式时,返回一个由捕获组捕获的子字符串组成的数组。然后,您可以访问通过该阵列捕获的内容。 E.g:
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]);
}
答案 1 :(得分:11)
phrase.match(/phrase=(.*)/)[1]
返回
"thisiswhatIwantmatched"
括号指定所谓的捕获组。捕获组的内容放入结果数组中,从1开始(0是整个匹配)。
答案 2 :(得分:0)
试试这个,我希望它有效
UIView *annotView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
annotView.backgroundColor = [UIColor redColor];
NMAMapOverlay *overlay = [[NMAMapOverlay alloc] initWithSubview:annotView];
overlay.coordinates = //your location's NMAGeoCoordinates
[self.mapView addMapOverlay:overlay];
答案 3 :(得分:0)
这并不难,只是假设你的背景是:
const context = https://medicoads.net/pa/GIx89GdmkABJEAAA+AAAA
我们希望在pa/
之后拥有该模式,因此请使用以下代码:
const pattern = context.match(/pa\/(.*)/)[1];
第一项包括pa/
,但对于分组第二项没有pa/
,您可以使用您想要的每一项。
答案 4 :(得分:0)
如果您想在正则表达式之后获取价值(不包括测试词组),请使用以下命令:
/(?:phrase=)(.*)/
结果将是
0: "phrase=thisiswhatIwantmatched" //full match
1: "thisiswhatIwantmatched" //matching group