我有一封标准电子邮件,希望从中提取某些详细信息。
电子邮件中包括以下行:
<strong>Name:</strong> John Smith
因此,为了模拟这一点,我具有以下JavaScript:
var str = "<br><strong>Name:</strong> John Smith<br>";
var re = /\<strong>Name\s*:\<\/strong>\s*([^\<]*)/g
match = re.exec(str);
while (match != null) {
console.log(match[0]);
match = re.exec(str);
}
这只会产生一个结果,即:
<strong>Name:</strong> John Smith
我希望获得捕获组([^\<]*)
,在这个示例中John Smith
我在这里想念什么?
在匹配数组中从索引1开始提供捕获组:
var str = "<br><strong>Name:</strong> John Smith<br>";
var re = /\<strong>Name\s*:\<\/strong>\s*([^\<]*)/g
match = re.exec(str);
while (match != null) {
console.log(match[1]); // <====
match = re.exec(str);
}
索引0包含整个匹配项。
在现代JavaScript引擎上,您还可以使用命名捕获组((?<theName>...)
,您可以通过match.groups.theName
以下方式进行访问:
var str = "<br><strong>Name:</strong> John Smith<br>";
var re = /\<strong>Name\s*:\<\/strong>\s*(?<name>[^\<]*)/g
// ---------------------------------------^^^^^^^
match = re.exec(str);
while (match != null) {
console.log(match.groups.name); // <====
match = re.exec(str);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句