Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx: Match one of two patterns

Tags:

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?

like image 414
Leopold Stotch Avatar asked Dec 22 '14 15:12

Leopold Stotch


People also ask

How do I match a pattern in regex?

Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .

What is ?! In regex?

The ?! n quantifier matches any string that is not followed by a specific string n.

How can I add two regex patterns?

to combine two expressions or more, put every expression in brackets, and use: *?

What is multiline in regex?

Multiline option, or the m inline option, enables the regular expression engine to handle an input string that consists of multiple lines. It changes the interpretation of the ^ and $ language elements so that they match the beginning and end of a line, instead of the beginning and end of the input string.


1 Answers

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}))$ 
like image 80
Avinash Raj Avatar answered Sep 19 '22 21:09

Avinash Raj