Home > Back-end >  Python Regex match date and value
Python Regex match date and value

Time:11-17

I'm trying to formulate an expression to capture the following text

  • 14-Oct-2021 15:27:12
  • AVG_CH10_CH11_CH12_CH13:0.553
  • CH10:24
  • CH11:-0.637
  • CH12:-0.193
  • CH13:0.036

tried the following Regex:

pattern = re.compile(r'\d{2}-\w{3}-\d{4} \d{2}:\d{2}:\d{2}|(?<=CH\d{2}:)(-?\d.*)')

with open(oFILE,'r') as f:
 matches = re.findall(pattern, f.read())

the pattern I have now only returns only the values for me but not the date, any help is much appreciated !

Goal values only:

  • 14-Oct-2021 15:27:12
  • 0.553
  • 24
  • -0.637
  • -0.193
  • 0.036

CodePudding user response:

Your regex seems to be getting your desired results for me:

import re

pattern = re.compile(r'\d{2}-\w{3}-\d{4} \d{2}:\d{2}:\d{2}|(?<=CH\d{2}:)(-?\d.*)')

tests = """14-Oct-2021 15:27:12
AVG_CH10_CH11_CH12_CH13:0.553
CH10:24
CH11:-0.637
CH12:-0.193
CH13:0.036""".splitlines()

for t in tests:
    match = pattern.search(t)
    print(match.group(0))

Result:

14-Oct-2021 15:27:12
0.553
24
-0.637
-0.193
0.036

CodePudding user response:

pattern = re.compile("\d{2}-\w{3}-\d{4} \d{2}:\d{2}:\d{2}|CH\d{2}:\d*|AVG_(CH\d{2}_)*(CH\d{2}):\d*")
str = "14-Oct-2021 15:27:12"
str2 = "CH11:-0.637"
str3 = "CH10:24"
str4 = "AVG_CH10_CH11_CH12_CH13:0.553"
print(pattern.match(str))
print(pattern.match(str2))
print(pattern.match(str3))
print(pattern.match(str4))

i' not sure why you addd '(?<=' to your code, here is my solution, wish it could help

CodePudding user response:

Thanks everyone for helping! the grouping at the end was the problem

Previous Regex:

\d{2}-\w{3}-\d{4} \d{2}:\d{2}:\d{2}|(?<=CH\d{2}:)(-?\d.*)

Updated Regex:

\b\d{2}-\w{3}-\d{4} \d{2}:\d{2}:\d{2}|(?<=CH\d{2}:)-?[\d.] 
  • Related