Search code examples
regexphone-number

Singapore mobile number regex with spaces in between


I am trying to make a regular expression that matches Singapore phone numbers. The key part is that the numbers may or may not have spaces in between.

My requirements are:

  1. The number should start with +65.
  2. The next number should be either 6, 8, or 9.
  3. The next 7 characters should be any digit from 0 to 9.

For example: +6581234567

I searched through Stack Overflow and found this question which does the exact same thing above.

Now like I said above, there could be spaces in between. And I'm not sure how to do the spaces. So the possible combinations are these two.

  1. +6581234567
  2. +65 8123 4567

Solution

  • ^\+65(\s?)[689]\d{3}\1\d{4}$
    

    This will allow any whitespace symbol after +65 and before last 4 digits.

    • ^ and $ start and end of the string,
    • \+65 matches literal "+65",
    • (\s?) matches an optional whitespace character. Caprured into group #1, and matched content will later be back referenced as \1,
    • [689] matches any one of digits: 6, 8, or 9,
    • \d{3} and \d{4} matches three and four digits accordingly,
    • \1 matches the same content that was in group #1.

    Demo here.