Strange result with simple regex

I am working on regex right now and am experiencing strange behavior:

The following regex takes Q-123456-789

orQ-123456-789

params: '^\\q\\-\\d{6}\\-\\d{3}$|^\\Q\\-\\d{6}\\-\\d{3}$'

      

The following regex accepts R-123456-789

but does notR-123456-789

params: '^\\r\\-\\d{6}\\-\\d{3}$|^\\R\\-\\d{6}\\-\\d{3}$'

      

(I just replaced q

with r

and q

with r

)

+3


source to share


3 answers


Because:

\r

matches a carriage return

but \q

only matches a literal q

.

Your regex is using redundant escaping, it should be without\\

ie



"^[qQ]-\\d{6}-\\d{3}$"

      

OR

"^[rR]-\\d{6}-\\d{3}$"

      

+1


source


\r

matches a carriage return (0x0D is a non-printable character), not a character r

. whereas it \q

matches a character q

.



If you want to combine r

, or r

simply replace it in a character class: ^[rR]

.

0


source


Try [r]

for an exact match instead of \r

for the expected result

Try the following:

^[rR]-\d{6}\-\d{3}$

      

Use https://regex101.com/#javascript for testing

0


source







All Articles