python Regex- get match based on condition

Viewed 137

I have the below text string

text = "\n1.2.2. ROAD LOAD PARAMETERS \nf0 \n227.4 \nf1 (N/(km/h)) \n0.149"

I am trying to write a regex match pattern to get values (consecutive 2 values) that follows '1.2.2. ROAD LOAD PARAMETERS'.

Expected output:

1.2.2. ROAD LOAD PARAMETERS : f0 227.4 # (only 2 values after the match)

Tried the below regex:

ec = re.search(r'(1.2.2. ROAD LOAD PARAMETERS)\s*(.+)', text)

ec.groups()

which gives me the following

('1.2.2. ROAD LOAD PARAMETERS', 'f0 ')
4 Answers

If the 1.2.2. ROAD LOAD PARAMETERS is always fixed you can use this:

ec = re.search(r'(1.2.2. ROAD LOAD PARAMETERS)\s+(\w+)\s+([\w\.]+)', text)

I replaced the .+ with \w+ in the first case to prevent matching the space, and also used [\w\.]+ in the second case because you have alphanumerical plus a ..

You can use the str.split() method:

import re

text = "\n1.2.2. ROAD LOAD PARAMETERS \nf0 \n227.4 \nf1 (N/(km/h)) \n0.149"

i = "1.2.2. ROAD LOAD PARAMETERS"

val1, val2 = text[text.index(i) + len(i):].split()[:2]
print(i, ":", val1, val2)

Output:

1.2.2. ROAD LOAD PARAMETERS : f0 227.4

You need two of the \s*(.+) if you want to match two numbers. Using

ec = re.search(r'(1.2.2. ROAD LOAD PARAMETERS)\s*(.+)\s*(.)', text)

gives you

('1.2.2. ROAD LOAD PARAMETERS', 'f0 ', '227.4 ')

You can use

import re
text="\n1.2.2. ROAD LOAD PARAMETERS \nf0 \n227.4 \nf1 (N/(km/h)) \n0.149"
m = re.search(r'\b(1\.2\.2\. ROAD LOAD PARAMETERS).*((?:\n.*){2})', text)
d = {}
if m:
    d[m.group(1).strip()] = m.group(2).replace('\n', '').strip()

print(d)
## => {'1.2.2. ROAD LOAD PARAMETERS': 'f0 227.4'}

See the Python demo.

The \b(1\.2\.2\. ROAD LOAD PARAMETERS).*((?:\n.*){2}) regex matches

  • \b - a word boundary
  • (1\.2\.2\. ROAD LOAD PARAMETERS) - Group 1: a fixed string
  • .* - any zero or more chars other than line break chars as many as possible
  • ((?:\n.*){2}) - Group 2: two occurrences of a line feed char followed with any zero or more chars (two lines after the line containing 1.2.2. ROAD LOAD PARAMETERS).

When building the dictionary you need to remove all line feeds from Group 2.

Related