javascript - .match 和捕获组如何协同工作?

标签 javascript regex

我应该创建一个正则表达式来匹配字符串中出现三次的数字,每个数字用空格分隔。但我不知道 .match() 方法和捕获组如何工作。

所以我有以下内容:

let repeatNum = "42 42 42";
let reRegex = /(\d+)\s\1/; // Change this line
let result = repeatNum.match(reRegex);
console.log(result);

结果是:

["42 42", "42"]

好吧,我有点明白为什么这个数组的第一个元素是“42 42”。

正则表达式:

/(\d+)\s\1/

表示标识一个或多个数字和一个空格。您将该单词放入第 1 组,然后让我在该空格后找到另一个与第 1 组相同的单词。

我已经看到了这个正则表达式如何在双字示例中工作。但我不知道对于三个或更多相同的数字如何工作?

编辑:我刚刚发现 42 42 42 42 的结果是相同的。现在我更困惑了。

最佳答案

JavaScript 正则表达式对象没有 match 方法。您可能会想到字符串上的一个:(Casimir et Hippolyte已在问题中为您更改了它)

let repeatNum = "42 42 42";
let reRegex = /(\d+)\s\1/; // Change this line
let result = repeatNum.match(reRegex);
console.log(result);

String#match 返回一个数组,其中包含总体匹配作为第一个条目,后跟任何捕获组的内容作为数组中的后续条目。这就是为什么您会得到 ["42 42", "42"]:"42 42" 是表达式的整体匹配,"42" 是第一个捕获组的内容。

如果您只想整体匹配,只需使用数组中的第一个条目即可。

I am supposed to make a regex to match numbers that appear three times in a string each separated by a space.

你的正则表达式不会这样做。它将尝试在字符串中匹配相同数字两次

如果您想匹配相同数字三次,则只需另一个\s\1:

let repeatNum = "42 42 42";
let reRegex = /(\d+)\s\1\s\1/;
let result = repeatNum.match(reRegex);
console.log(result ? result[0] : "No match");

如果你只想匹配以空格分隔的数字,最简单的就是使用 \d+\s\d+\s\d+:

let repeatNum = "42 43 44";
let reRegex = /\d+\s\d+\s\d+/;
let result = repeatNum.match(reRegex);
console.log(result ? result[0] : "No match");

...尽管您可以根据需要使用 \d+(?:\s\d+){2},它表示“一系列数字后跟两个实例:后跟一个空格由一系列数字组成。”

let repeatNum = "42 43 44";
let reRegex = /\d+(?:\s\d+){2}/;
let result = repeatNum.match(reRegex);
console.log(result ? result[0] : "No match");

I just found out the result is the same for 42 42 42 42

如果没有 anchor ,正则表达式将在字符串中查找匹配项;它不要求匹配整个字符串。因此,当您针对 "42 42 42 42" 运行上述任何内容时,您将看到与在 "42 42 42" 上使用它时相同的内容,因为它匹配一个子字符串。

如果您只想匹配整个内容,请在开头添加 ^ 并在末尾添加 $。这些是输入断言的开始/结束。

例如,上面的第一个更改(对正则表达式的最小更改):

let repeatNum = "42 42 42";
let reRegex = /^(\d+)\s\1\s\1$/;
let result = repeatNum.match(reRegex);
console.log("repeatNum:", result ? result[0] : "No match");
let repeatNum2 = "42 42 42 42";
result = repeatNum2.match(reRegex);
console.log("repeatNum2:", result ? result[0] : "No match");

关于javascript - .match 和捕获组如何协同工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44485797/

相关文章:

regex - 在 Bash 中将 vim 替换为 sed/awk

c# - 消除字符串中多余的字母? (例如 gooooooooood -> 好)

javascript - jQuery.proxy 与 underscore.bind

javascript - 在 signalR 核心启动时设置自定义 ID

javascript - ES6 : access to inherited class'es properties and methods from the parent class

regex - Smarty 正则表达式匹配

c++ - 使用 std::regex 调用 abort() 来验证 URL

c# - 正则表达式来替换之前没有特定单词的单词

javascript - 使用 jQuery 查找和替换 HTML

javascript - 可以在 webpack.config.js 中链接 Node 模块文件吗?