Gakis41
Gakis41

Reputation: 1840

python match string in line with regex and get a certain value

I have the following which is part of a line in a log file

-FDH-11 TIP: - 146/S Q: 48

which I want to match with regex . Is there a way to get the value of Q in the above input. I am not sure the length between -FDH- and Q: is always the same. So ideally if I found -FDH- and Q: then get the value of Q.

Upvotes: 0

Views: 40

Answers (2)

ctwheels
ctwheels

Reputation: 22817

Code

See regex in use here

-FDH-.*?\bQ:\s*(\S+)

Explanation

  • -FDH- Match this literally
  • .*? Match any character any number of times, but as few as possible
  • \b Assert position as a word boundary
  • Q: Match this literally
  • \s* Match any number of whitespace characters
  • (\S+) Capture one or more non-whitespace characters into capture group 1

Upvotes: 3

user3354059
user3354059

Reputation: 402

You probably don't need to use regex for this. If there is only one instance of "Q:" in the string, then you can just split on that and get the value after with the following:

str = "-FDH-11 TIP: - 146/S Q: 48"
parts = str.split("Q: ")
q_value = parts[1]

Upvotes: 0

Related Questions