简体   繁体   English

Javascript 正则表达式 - 重用模式来捕获组

[英]Javascript regex - reusing patterns to capture groups

I'm just trying to learn javascript regex and have been stuck on this problem for a while.我只是想学习 javascript 正则表达式并且已经在这个问题上停留了一段时间。

I need to match patterns, some examples below:我需要匹配模式,下面是一些示例:

console.log("42 42 42 42".match(reRegex)); // should NOT match
console.log("42 42".match(reRegex)); // should NOT match
console.log("42 42 42".match(reRegex)); // should match

I have tried a lot of versions of this, but can't figure it out.我已经尝试了很多版本,但无法弄清楚。 Can you tell me how this works?你能告诉我这是如何工作的吗?

This is incorrect as it matches 42 42 42 42 , which it shouldn't.这是不正确的,因为它不应该匹配42 42 42 42

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

Thanks谢谢

Have alook at anchors看看

Add a $ if it is per line: /^(\d+)(\s)\1\2\1$/如果是每行,则添加 $: /^(\d+)(\s)\1\2\1$/

https://regex101.com/r/FFwPWF/1 https://regex101.com/r/FFwPWF/1

You can add ^ at the beginning and add $ at the end of your regex.您可以在正则表达式的开头添加^并在结尾添加$

https://regex101.com/r/7EUpOb/2 https://regex101.com/r/7EUpOb/2

Regex101 is a good reference and has good explanation during execution of regex! Regex101 是一个很好的参考,在执行正则表达式时有很好的解释!

Here is a possible Solution这是一个可能的解决方案

let repeatNum = "42 42 42";
let reRegex = /^(\d{2,3})(\s)\1\2\1$/; // Change this line
let result = reRegex.test(repeatNum);

It was matching also 42 42 42 42 so you have to limit the regex by adding string anchors at the beginning and end of the regex它也匹配42 42 42 42所以你必须通过在正则表达式的开头和结尾添加字符串锚来限制正则表达式

/^(\d{2,3})[ ]\1[ ]\1$/

\d{2,3} - should match only 2-3 digit number.
[ ] - Only space character
\1 - captured group 1
^ - beginning of the line.
$ - end of the line

Tested this expression in the link you gave and it passes all tests.在您提供的链接中测试了这个表达式,它通过了所有测试。

https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/reuse-patterns-using-capture-groups https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/reuse-patterns-using-capture-groups

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM