Wang Mei Ling
Wang Mei Ling

Reputation: 41

How can I allow one space in a regular expression

The following Regex checks for a number which starts with 6, 8 or 9 and has to be exactly 8 digits long.

/^(6|8|9)\d{7}$/

Now I want to accept one space in between digits as well, but don't know where to start.

For example both 61234567 and 6123 4567 should be allowed, but only the first one passes my current regex.

Can you help me create it?

Upvotes: 4

Views: 70

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

You could use the regular expression

/^[689](?:\d{7}|(?=.{8}$)\d* \d+)$/

demo

We can make this self-documenting by writing it in free-spacing mode:

/
^            # match beginning of line
[689]        # match '6', '8' or '9'
(?:          # begin non-capture group
  \d{7}      # match 7 digits
  |          # or
  (?=.{8}$)  # require the remainder of the line to have 8 chars
  \d*\ \d+   # match 0+ digits, a space, 1+ digits 
)            # end non-capture group
$            # match end of line
/x           # free-spacing regex definition mode

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You may use

^(?!.*(?:\s\d+){2})[689](?:\s?\d){7}$

See the regex demo

Details

  • ^ - start of string
  • (?!.*(?:\s\d+){2}) - a negative lookahead that fails the match if, after any 0+ chars other than line break chars, as many as possible occurrences, there are two occurrences of a whitespaces followed with 1+ digits
  • [689] - 6, 7 or 9
  • (?:\s?\d){7} - seven occurrences of an optional whitespace followed with a single digit
  • $ - end of string.

To allow leadign/trailing whitespace, add \s? (1 or 0) or \s* (0 or more) right after ^ and before $.

To allow a single 1+ more whitespace chunk in the digit string, use

^(?!.*(?:\s+\d+){2})[689](?:\s*\d){7}$

See this regex demo.

Upvotes: 1

Related Questions