olefrank
olefrank

Reputation: 6820

Regex with multiplier for single character inside character set

I need a Regex for validating a phone number. White space allowed (but only one at a time).

OK: +45 1234 1234

NOT OK: +45 1234 1234

OK: 0045 54 45 45 45

NOT OK: 0045 54 45 45 45

I tried /^[+]?[0-9\s-]*$/ but it's not working as it allows for multiple white space.

Upvotes: 1

Views: 434

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627380

Your ^[+]?[0-9\s-]*$ regex matches a string that starts with an optional plus ([+]?) and then has an unlimited amount (0 or more) of digits, whitespaces or hyphens, thus, it even matches "+ --- " string:

enter image description here

You need to use

/^\+?[0-9]+(?:[\s-][0-9]+)*$/

See the regex demo and the regulex graph:

enter image description here

Mind to keep - at the end of the character class in [\s-] if you want to keep it unescaped, or escape the hyphen inside the character class, [\s\-].

Details

  • ^ - start of a string
  • \+? - an optional + symbol
  • [0-9]+ - one or more digits
  • (?:[\s-][0-9]+)* - a non-capturing group that matches 0 or more repetitions of
    • [\s-] - a character class matching a single whitespace or -
    • [0-9]+ - 1 or more digits
  • $ - end of string

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44145

Try using this regex:

var re = /^\+?\d+(\s\d+)*$/;
var strings = ["+45 1234 1234", "+45  1234 1234", "0045 54 45 45 45", "0045 54  45 45   45"];
strings.forEach(s => console.log(s.match(re)));

Upvotes: 1

Related Questions