如何在JavaScript正则表达式中访问匹配的组? [英] How do you access the matched groups in a JavaScript regular expression?

查看:127
本文介绍了如何在JavaScript正则表达式中访问匹配的组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用正则表达式匹配字符串的一部分,然后访问括号内的字符串substring:

I want to match a portion of a string using a regular expression and then access that parenthesized substring:

var myString = "something format_abc"; // I want "abc"

var arr = /(?:^|\s)format_(.*?)(?:\s|$)/.exec(myString);

console.log(arr);     // Prints: [" format_abc", "abc"] .. so far so good.
console.log(arr[1]);  // Prints: undefined  (???)
console.log(arr[0]);  // Prints: format_undefined (!!!)

我做错了什么?

我发现上面的正则表达式代码没有任何问题:我测试的实际字符串是:

I've discovered that there was nothing wrong with the regular expression code above: the actual string which I was testing against was this:

"date format_%A"

报告%A未定义似乎是一种非常奇怪的行为,但它与此问题没有直接关系,所以我打开了一个新的, 为什么匹配的子字符串在JavaScript中返回undefined?

Reporting that "%A" is undefined seems a very strange behaviour, but it is not directly related to this question, so I've opened a new one, Why is a matched substring returning "undefined" in JavaScript?.

问题是 console.log 将其参数视为一个 printf 语句,因为我记录的字符串(%A)有一个特殊值,它是试图找到下一个参数的值。

The issue was that console.log takes its parameters like a printf statement, and since the string I was logging ("%A") had a special value, it was trying to find the value of the next parameter.

推荐答案

你可以像这样访问捕获组:

You can access capturing groups like this:

var myString = "something format_abc";
var myRegexp = /(?:^|\s)format_(.*?)(?:\s|$)/g;
var match = myRegexp.exec(myString);
console.log(match[1]); // abc

如果有多个匹配项,您可以迭代他们:

And if there are multiple matches you can iterate over them:

var myString = "something format_abc";
var myRegexp = /(?:^|\s)format_(.*?)(?:\s|$)/g;
match = myRegexp.exec(myString);
while (match != null) {
  // matched text: match[0]
  // match start: match.index
  // capturing group n: match[n]
  console.log(match[0])
  match = myRegexp.exec(myString);
}

这篇关于如何在JavaScript正则表达式中访问匹配的组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆