Regex that match exactly 3 identical consecutive numbers

Rol*_* Co 6 javascript regex capturing-group

Good morning all,

I want to make a regex that match 3 same consecutive numbers. It should match only 3 numbers in a row (separated by a space), the numbers should be identical. If there are less or more than 3 same numbers, then the output should be false

I have tried this regex /.*(\d+) \1 \1(?!(\s\1))/

console.log(/.*(\d+) \1 \1(?!(\s\1))/.test('I am 42 42 4 hey yoo')); //false --> Correct
 
console.log(/.*(\d+) \1 \1(?!(\s\1))/.test('I am 42 42 42 hey yoo')); //true --> Correct

console.log(/.*(\d+) \1 \1(?!(\s\1))/.test('I am 42 42 42 4 hey yoo')); //true --> Correct

console.log(/.*(\d+) \1 \1(?!(\s\1))/.test('I am 42 42 42 42 hey yoo')); //true --> this output should be false since there are 4 same consecutive digits
Run Code Online (Sandbox Code Playgroud)

Any advice, please?

Car*_*and 3

我假设三个相同的数字字符串由一个空格分隔,这三个数字的组中的第一个位于字符串的开头,或者前面有一个空格,该空格前面没有相同的字符串,最后一个字符串是这三个组位于字符串的末尾,或者后面跟有一个空格,但后面没有跟同一个字符串。

您可以尝试匹配以下正则表达式。

(?: |^)(\d+)(?<!(?: |^)\1 \1)(?: \1){2}(?![^ ]| \1(?: |$))
Run Code Online (Sandbox Code Playgroud)

演示

正则表达式可以分解如下。(或者,将光标悬停在链接处表达式的每个部分上以获得其功能的说明。)

(?: |^)     # match a space or the beginning of the string
(\d+)       # match one or more digits and save to capture group 1
(?<!        # begin a negative lookbehind
  (?: |^)    # match a space or the beginning of the string
  \1 \1      # match the content of capture group 1 twice, separated by a space
)           # end the negative lookbehind
(?: \1)     # match a space followed by the content of capture group 1
{2}         # execute the preceding non-capture group twice
(?!         # begin a negative lookahead
  [^ ]        # match a character other than a space
  |           # or
   \1         # match a space followed by the content of capture group 1
  (?: |$)     # match a space or the end of the string
)           # end the negative lookahead
Run Code Online (Sandbox Code Playgroud)

请注意,(?: .... )表示非捕获组。