Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

197
Views
Regex length check account for optional group
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)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!