Home > Enterprise >  How to match numbers and text separated by underscore?
How to match numbers and text separated by underscore?

Time:07-05

I have this string:

my_str = '25.06.2022_21.28.32_MyText_Here_10.103.155.10\fileName.txt'

I need to extract the following data separately:

  • 25.06.2022
  • 21.28.32
  • MyText_Here (can be with _ or without it)
  • 10.103.155.10

I tried get it with re.search but failed to find the correct syntax:

matches = re.search(r'(\d .\d .\d )_(\d .\d .\d )_([a-z,_])(\d .\d .\d .\d )', my_str)

results: matches - None

CodePudding user response:

Try (regex101):

import re

my_str = r"25.06.2022_21.28.32_MyText_Here_10.103.155.10\fileName.txt"

matches = re.search(
    r"(\d \.\d \.\d )_(\d \.\d \.\d )_(.*?)_(\d \.\d \.\d \.\d )", my_str
)

print(*matches.groups(), sep="\n")

Prints:

25.06.2022
21.28.32
MyText_Here
10.103.155.10

CodePudding user response:

Please try this code:

import re

my_str = '25.06.2022_21.28.32_MyText_Here_10.103.155.10'

m = re.match('^([\d\.] )\_([\d\.] )\_(. )\_([\d\.] )', my_str)

if m:
    f1 = m.group(1)
    f2 = m.group(2)
    f3 = m.group(3)
    f4 = m.group(4)
    print(f'f1 = {f1}')
    print(f'f2 = {f2}')
    print(f'f3 = {f3}')
    print(f'f4 = {f4}')
  • Related