My regex is not working

Asked

Viewed 42 times

0

I made a regular expression for mobile, on the site https://regex101.com/ is working, but in my project no, follows below the example

My Pattern in the code: telefone: [null, [Validators.required, Validators.pattern('(\(\d{2}\)\ \d{1}\ \d{4}\-\d{4})')]]

String used for testing on the website https://regex101.com/ : (00) 0 0000-0000

print do site https://regex101.com/

1 answer

1


The pattern is receiving a string, and within strings the character \ must be escaped and written as \\. Then it would be:

Validators.pattern("\\(\\d{2}\\) \\d \\d{4}-\\d{4}")

Also, notice that space and hyphen don’t need the \ before, and the quantifier {1} is unnecessary because \d{1} is the same as \d.

I also took the parentheses around the expression, which don’t seem to make a difference here.


Another alternative is to use the literal syntax of regex, delimiting it by bars, so you don’t need to escape the \:

Validators.pattern(/^\(\d{2}\) \d \d{4}-\d{4}$/)

I included the markers ^ and $, which indicate the beginning and end of the string. In the first case, you do not need it because according to the documentation, when passing a string, these markers are automatically added.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.