Tzimpo
Tzimpo

Reputation: 1009

Regex allow only one dash or only one space

I want an expression that allows number and one dash OR number and one space. Space or dash are optional. I tried this

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

Accepted regular expressions:

  1. 11-222
  2. 444 99

Upvotes: 0

Views: 642

Answers (2)

Toto
Toto

Reputation: 91373

Let's explain your regex.

  ^                   # beginning of line
    (                   # start group 1
        [0-9]+          # 1 or more digits
        (               # start group 2
            -           # a hyphen
            [0-9]+      # 1 or more digits
        )?              # end group 2, optional
    )                   # end group 1
|                   # OR
    (                   # start group 3
        [0-9]+          # 1 or more digits
        (               # start group 4
            \s          # a space
            [0-9]+      # 1 or more digits
        )?              # end group 4, optional
    )                   # end group 3
  $                   #  end of line

The OR acts between the group 1 at the beginning of the line and the group 3 at the end of the line. But you want group 1 and group 3 anchored at the beginning and at the end.

Add a group over group 1 and 3:

^(([0-9]+(-[0-9]+)?)|([0-9]+(\s[0-9]+)?))$

You can use non capture groups (more efficient) instead of capture group

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

Combine the hyphen and the space in a character class and remove the superfluous groups:

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

If your regex flavour supports it, change the [0-9] into \d. Finally your regex becomes:

^\d+(?:[-\s]\d+)?$

Much simpler, no?

Upvotes: 1

M. Bauer
M. Bauer

Reputation: 199

You can put the OR in the middle of your expression: ^([0-9]+)(\s|-)([0-9]+)$ works with your examples in Notepad++.

Upvotes: 2

Related Questions