0

I am using Regex for the first time and I've stumbled upon something quite unpleasing... I'm looking for a format that is sometimes "two digits | four digits" or "three digits | four digits". The problem is that when called only first part of the digit string is displayed. And I'm having this problem because of the | separator between the digits, because if I put / in between instead of | everything is displayed normally.

My code at the moment is like this:

import re

string = '554 | 8888'

# Three digit number followed by | followed by two digit number

pattern1 = r"(\d{3}) | (\d{4})"
pattern2 = r'(\d{2}) | (\d{4})'

# match variable contains a Match object.

match1 = re.search(pattern1, string)
match2 = re.search(pattern2, string)

if match1:
    print(match1.group())

elif match2:
    print(match2.group())
else:
    print("pattern not found")

And if i run the program I get:

"554" instead of "554 | 8888"

Any solutions and improvements are very welcome :)

0 Answers0