如何在Javascript正则表达式中捕获组?

令状

我试图customer.namehello @customer.name文本字符串的末尾捕获

但是,我似乎无法从中@脱颖而出。它给@customer.name

现在,我的正则表达式为:

@([0-9a-zA-Z.]+)$
插口

使用.match字符串方法。结果将是null与给定的正则表达式不匹配,否则它将是一个数组,其中:

  • 根据@customer.name您的情况,第一个元素是整个匹配的字符串
  • 其余元素是每个捕获组。您有一个捕获组,因此最终将在第一个索引中。在您的情况下,这将是customer.name所需的字符串。

看到这个片段。您的正则表达式看起来已经正确,您只需要从其中拉出捕获组,而不是整个匹配的字符串即可。

const str = "hello @customer.name"
const reg = /@([0-9a-zA-Z.]+)$/;

const match = str.match(reg)
console.log(match)
console.log("Matched string:", match[0]);
console.log("First capture group:", match[1]);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章