0

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.

10
  • 2
    -FDH-.*?\bQ:\s*(\S+)? Commented Dec 1, 2017 at 17:40
  • There can be more Q's between FDH or not? Would be ok to look just for the FDH and then for the Q? Commented Dec 1, 2017 at 17:40
  • @fernand0 No other Q in line and yes for the second part of your question. Thanks guys!! Commented Dec 1, 2017 at 17:46
  • @Gakis41 if there are no other instances of Q: in the string, the solution below provided by user3354059 should work for you. Commented Dec 1, 2017 at 17:47
  • @ctwheels on a regex editor it does the job right!!Thanks Commented Dec 1, 2017 at 17:49

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

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]

3 Comments

What if there's another variable with a Q in it like GQ:? The user also specified that it should be after -FDH-, which might imply that other instances exist where Q might be found. I do agree, however, that the OP should present us with more information about the string.
Then it wouldn't work which is why I said there can only be one instance of "Q:", but I was just trying to present the simplest and easiest to implement possible answer based on the above input. It won't work if your example occurs.
@ctwheels Q should be alone with a ":" in front.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.