如何用正则表达式拿到匹配到的值
使用正则表达式的match方法可以返回匹配到的值,例如:
const str = 'Hello, world!';
const regex = /world/;
const matchResult = str.match(regex);
console.log(matchResult); // ["world"]
match方法返回一个数组,第一个元素是匹配到的字符串,后面的元素是匹配到的分组(如果有的话)。
如果需要获取多个匹配结果,可以使用全局匹配(g):
const str = 'Hello, world! Hello, everyone!';
const regex = /Hello/g;
const matchResult = str.match(regex);
console.log(matchResult); // ["Hello", "Hello"]
match方法也可以使用捕获组,可以通过索引访问:
const str = 'john@example.com, jane@example.com';
const regex = /(\w+)@example\.com/g;
let matchResult;
while (matchResult = regex.exec(str)) {
console.log(matchResult[0]); // 匹配到的完整字符串
console.log(matchResult[1]); // 第一个捕获组
}
除了match方法之外,还有其他一些正则表达式方法也可以返回匹配结果,例如exec方法和test方法。
原文地址: https://www.cveoy.top/t/topic/whB 著作权归作者所有。请勿转载和采集!