Home > Blockchain >  How to escape curly braces in RegExp
How to escape curly braces in RegExp

Time:10-23

I want to escape curly braces in my regular expression. Unfortunately the \\ does not work. The problem is that the regular expression does not work on IOS mobile devices.

The regular expression is used in Angular forms:

Validators.pattern('(?<!\w)(\(?(\ |00)?48\)?)?[ -]?\d{3}[ -]?\d{3}[ -]?\d{3}(?!\w)');

Whenever I enter the site that does use this expression on IOS mobile device, then I can see in chrome errors related to regular expression. If I delete this pattern, then the site works without any problems.

CodePudding user response:

Pass RegExp instance instead of direct string

Validators.pattern(new RegExp(/^(?<!\w)(\(?(\ |00)?48\)?)?[ -]?\d{3}[ -]?\d{3}[ -]?\d{3}(?!\w)$/, 'i'))

CodePudding user response:

This validation looks suspicious: (?<!\w)/(?!\w) unambiguous word boundaries are used to circumvent the problem with \b word boundaries when there is a chance that the adjoining character type may be different (word and non-word). It only makes sense when you match whole words in a longer string.

Angular validation for a phone number is meant to match the whole string, so I recommend just removing these lookarounds. You do not even need to add ^ at the start and $ at the end since these anchors are added by Angular to any regex passed to Validators.pattern() as a string literal, "..." (as opposed to regex literal, /.../).

However, it is not all: you are defining the regex with a string literal, so you need to double the backslashes in your string.

You can use

Validators.pattern('(\\(?(\\ |00)?48\\)?)?[ -]?\\d{3}[ -]?\\d{3}[ -]?\\d{3}');
  • Related