Char regular expression only if a specific char appears (conditional regular expression)

development of a mobile (Israeli) regex phone number. I currently have

re.compile(r'^[\(]?0?(5[023456789])\)?(\-)?\d{7}$') 

which catches most use cases. the problem matches the second bracket only if the first bracket appears.

therefore, (055) -5555555 or (055) 5555555 or 0555555555 would correspond but: 055) -5555555 would not. I know that I can use 2 regular expressions to test a condition (if the first matches the test for another condition), but this does not seem like an intelligent solution.

I think I need something like a regular search, but not sure how to use it, or that I understand the concept correctly.

Edit: explanation of logic

zone code: should start with 5, and then with one digit (from a specific list) with the option zero before. it is also possible that it would be in parentheses. then an optional hyphen and 7 digits

Clarfication: I need to match both brackets only if there is another that is true and for the first not only for the second, I skipped this point

+4
source share
2 answers

First you have to fix the opening bracket, and then use the conditional pattern (I know that the link to php.net, but I find it useful when referring to regular expressions, also includes an example that exactly matches your case), which will only apply to If the first opening bracket is matched.

Sample..

 ^(\()?0?(5[02-9])(?(1)\))-?(\d{7})$ 

Will match :

 (055)-5555555 (055)5555555 0555555555 

but not :

 055)-5555555 

Captured Groups

  • Initial bracket (empty if not found)
  • Area code (e.g. 55)
  • Phone number (e.g. 5555555)

How it works

The (\()? Part matches the opening bracket. This is optional.

Part (?(1)\)) checks whether the first captured group (in our case, the opening bracket) matches, if YES , then the line must also match the closing bracket.

If the initial bracket is not found, the condition is effectively ignored.

+9
source

Use the syntax (?(id/name)yes-pattern|no-pattern) so that it matches the closing parenthesis only if the matching paste:

 re.compile(r'^(\()?0?(5[023456789])(?(1)\))-?\d{7}$') 

The part (?(1)\)) matches \) if there is group 1 (the | no pattern is optional).

Demo:

 >>> phone.search('(055)-5555555') <_sre.SRE_Match object at 0x101e18a48> >>> phone.search('055)-5555555') is None True 
+3
source

All Articles