Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex expression with \1 references not matching desired string

I am working on this regex expression and i have confusion how it is working.

/^(\d+)\s\1\s\1$/

i know that

^ is start of line 
() shows capture group
\d+ shows digits 
\s is whitespace 
\1 shows to match first group
$ the end 

confusing part is $ here and why it is matching to "40 40 40 " but not "40 40 40 40" and role of $

like image 915
Maria Avatar asked Sep 09 '25 11:09

Maria


2 Answers

\1 refers to the first capturing group in the regular expression. \2 will refer to the second capturing group and \n will refer to an nth capturing group.

In the regular expression /^(\d+)\s\1\s\1$/. \1 will match the only group of digits which is matched by the first capturing group (\d+).

$ in /^(\d+)\s\1\s\1$/ Means it should end by one more digits.

^ in /^(\d+)\s\1\s\1$/ Means it should start by one more digits.

like image 112
Akshay Bande Avatar answered Sep 11 '25 02:09

Akshay Bande


$ matches "end of string". The way you have the regex pattern defined, it shouldn't match either of your strings because 40 40 40 has an extra space at the end before the end of string and 40 40 40 40 has extra space and digits after the third 40 and before the end of string.

If you remove the $, then it will match both of your strings or any string that begins with 40 40 40, so for example it will also match 40 40 40 test.

like image 32
Emrah Diril Avatar answered Sep 11 '25 01:09

Emrah Diril