Home > other >  Regex length check account for optional group
Regex length check account for optional group

Time:12-08

export const validUKPhone = /^(\ )?(44)?(\s*\d){9,11}$/;

I currently have the following RegEx for a telephone number, that is trying to validate the length of a number.

Now the fun bit of this, is that there are 3 optional characters at the start of the pattern. 44 (potentially).

My question is how to write my regex to take account for this group, and only count the length of the 'main body' of the number. If the 44 exists, the length pattern would be {12,14} otherwise {9,11}

e.g. The following test fails.

  expect(regex.test(' 440798444')).toBeFalsy();
  expect(regex.test(' 440798444457')).toBeTruthy(); 

(10 characters currently because of the 44 but returns true)

CodePudding user response:

You can use

/^(?:\ ?44|(?!44))(?:\s*\d){9,11}$/

See the regex demo. Details:

  • ^ - start of string
  • (?:\ ?44|(?!44)) - a non-capturing group matching:
    • \ ?44 - an optional and then 44
    • | - or
    • (?!44) - (a negative lookahead that matches) a location that is not immediately followed with 44 (add \s* if you do not want to match the number even if there are whitespaces before/inside 44)
  • (?:\s*\d){9,11} - nine to eleven occurrences of zero or more whitespaces and then a digit
  • $ - end of string.
  • Related