Query regarding Python Multiple Regex Expression

Viewed 50

I am new to Python, just trying to solve a few regex expressions, I was stuck with the below code. Kindly help me out on this.

import re
a = ["my mac is aa-bb-cc-33-44-SS","Hostname: xyz1"]
for i in a:
    c = re.findall(r"\\D{2}-\\D{2}-\\D{2}-\\d{2}-\\d{2}-\\D{2}|:(.\*)",i)
    print(c)

Output for above code is : [''] [' xyz1']

But the output really needed is ['aa-bb-cc-33-44-SS'] ['xyz1]

2 Answers

I can spot two mistakes in the code.

  1. if you use raw string you don't have to escape / or *
    so it would just be
    re.findall(r"\D{2}-\D{2}-\D{2}-\d{2}-\d{2}-\D{2}|:(.*)", i)
  2. you don't group the first expression:
    re.findall(r"(\D{2}-\D{2}-\D{2}-\d{2}-\d{2}-\D{2})|:(.*)", i)
>> a = ["my mac is aa-bb-cc-33-44-SS","Hostname: xyz1"]
>> for i in a:
>>     c = re.findall(r"(\D{2}-\D{2}-\D{2}-\d{2}-\d{2}-\D{2})|:(.*)", i)
>>     print(c)

[('aa-bb-cc-33-44-SS', '')]
[('', ' xyz1')]

You can use

(?:[^\d\s-]{2}-){3}\d{2}-\d{2}-[^\d\s-]{2}|(?<=:\s).+

See the regex demo. Details:

  • (?:[^\d\s-]{2}-){3} - three occurrences of two chars other than digits, whitespaces and hyphens followed with -
  • \d{2}-\d{2}- - two sequences of two digits and a - char
  • [^\d\s-]{2} - two chars other than digits, whitespaces and hyphens followed with -
  • | - or
  • (?<=:\s).+ - any one or more chars other than line break chars as many as possible (.+) that are immediately preceded with a colon and a whitespace.

In Python, use

re.findall(r'(?:[^\d\s-]{2}-){3}\d{2}-\d{2}-[^\d\s-]{2}|(?<=:\s).+', i)
Related