eMi
eMi

Reputation: 5628

RegEx no whitespace in third column of mobile number

I came up with following regex for a mobile phone number:

^\+([0-9]{1,} )+([0-9]{2,} )+[0-9]+

Example of valid number:

+385 552 8221520

What would be the according regex, so I don't get a match if any whitespace in the third capturing group is found:

+385 552 82215 20 (gives a match now, but not fine!)

Upvotes: 2

Views: 48

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627119

Your pattern contains quantified groupings. The ^\+([0-9]{1,} )+([0-9]{2,} )+[0-9]+ pattern matches a string that starts with +, then contains 1 or more repetitons of 1+ digits followed with a space, then 1+ repetitions of 2+ digits followed with a space and then 1+ digits. Thus, it matches many space separated digit chunks. Also, it is not anchored at the end of the string with $ and might match strings that contain rubbish at the end if used with a regex method that allows partial matches.

To limit to just three space separated digit chunks, you may use any of the following:

  • ^\+[0-9]+ +[0-9]{2,} +[0-9]+$ - if there can be 1 or more spaces between the digit groups
  • ^\+[0-9]+ ?[0-9]{2,} ?[0-9]+$ - if there can be 1 or 0 spaces between digit groups
  • ^\+[0-9]+ *[0-9]{2,} *[0-9]+$ - if there can be 0 or more spaces between digit groups.

Note that $ added at the end of each pattern. Also, see this regex demo.

Upvotes: 1

Related Questions