17

I have two regular expressions, one for validating a mobile number and one for a house phone number.

Mobile number pattern:

^((07|00447|\+447)\d{9}|(08|003538|\+3538)\d{8,9})$

Home number pattern:

((0|0044|\+44)\d{10}|(08)\d{9}|(90)\d{6}|(92)\d{6}|(437)\d{5}|(28)\d{6}|(37)\d{6}|(66)\d{6}|(82)\d{6}|(777)\d{5}|(93)\d{6})$

Is there a way to combine both of these expressions so that I can apply them to a 'Contact Number' field that would be valid if the input matched either expression?

Leopold Stotch
  • 1,252
  • 2
  • 11
  • 24
  • 5
    Consider bookmarking the [Stack Overflow Regular Expressions FAQ](http://stackoverflow.com/a/22944075/2736496) for future reference. – aliteralmind Dec 22 '14 at 16:02

3 Answers3

26

Put both regexes into a non-capturing group separated by an alternation operator |.

^(?:((07|00447|\+447)\d{9}|(08|003538|\+3538)\d{8,9})|((0|0044|\+44)\d{10}|(08)\d{9}|(90)\d{6}|(92)\d{6}|(437)\d{5}|(28)\d{6}|(37)\d{6}|(66)\d{6}|(82)\d{6}|(777)\d{5}|(93)\d{6}))$
Avinash Raj
  • 160,498
  • 22
  • 182
  • 229
5

Combine them with a pipe it's the or operator.

^((07|00447|\+447)\d{9}|(08|003538|\+3538)\d{8,9})|((0|0044|\+44)\d{10}|(08)\d{9}|(90)\d{6}|(92)\d{6}|(437)\d{5}|(28)\d{6}|(37)\d{6}|(66)\d{6}|(82)\d{6}|(777)\d{5}|(93)\d{6})$
Mouser
  • 12,807
  • 3
  • 25
  • 51
3

You can have to non-capturing groups with a | condition:

^(?:(07|00447|\+447)\d{9}|(08|003538|\+3538)\d{8,9})|(?:(0|0044|\+44)\d{10}|(08)\d{9}|(90)\d{6}|(92)\d{6}|(437)\d{5}|(28)\d{6}|(37)\d{6}|(66)\d{6}|(82)\d{6}|(777)\d{5}|(93)\d{6})$
nitishagar
  • 7,764
  • 3
  • 20
  • 35