Marcus
Marcus

Reputation: 31

Regular expression: numbers spaces parentheses +

I need a regular expression where any number is allowed with spaces, parentheses and hyphens in any order. But there must be a "+" (plus sign) at the end.

Upvotes: 3

Views: 5621

Answers (2)

Jakub Hampl
Jakub Hampl

Reputation: 40553

If the rules mean that the whole string must be according to them, then:

/^[\d\(\)\- ]+\+$/

This will match (i) 435 (345-325) + but not (ii) my phone is 435 (345-325)+, remember it.

If you want to just extract (i) from (ii) you could use my original RegExp:

/[\d\(\)\- ]+\+/

Upvotes: 1

codaddict
codaddict

Reputation: 455302

You can use the regex:

^[\d() -]+\+$

Explanation:

^   : Start anchor
[   : Start of char class.
 \d : Any digit
 (  : A literal (. No need to escape it as it is non-special inside char class.
 )  : A literal )
    : A space
 -  : A hyphen. To list a literal hyphen in char class place it at the beginning
      or at the end without escaping it or escape it and place it anywhere.
]   : End of char class
+   : One or more of the char listed in the char class.
\+  : A literal +. Since a + is metacharacter we need to escape it.
$   : End anchor

Upvotes: 15

Related Questions