I want to write a regex to pull the nth field from the end of a string in splunk. Please let me know how to proceed.
Asked
Active
Viewed 595 times
-3
-
It really depends on your code. Can you post your code as well as some sample strings (input/expected output). You may not even need regex for this. Also, please see [how do I ask a good question?](https://stackoverflow.com/help/how-to-ask), as well as [what topics can I ask about here?](https://stackoverflow.com/help/on-topic) and [how to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) to improve your question. Unfortunately, since your question doesn't respect any of these articles, I'm afraid it will likely be closed. – ctwheels Jan 09 '18 at 14:34
-
Exception field1 field2 500 x yz a b. would be a sample string. Status code is always printed as 5th field from end. I can’t guarantee its position from start. – Sarnath Jegadeesan Jan 09 '18 at 15:25
-
Use `(\S+)(?:\s+\S+){4}\s*$` or `\S+(?=(?:\s+\S+){4}\s*$)` – ctwheels Jan 09 '18 at 15:33
1 Answers
-1
Code
(\S+)(?:\s+\S+){4}\s*$
Alternatively, you can also use the following:
\S+(?=(?:\s+\S+){4}\s*$)
Explanation
Both methods use the same logic. The only difference is the first method captures the 5th element from the end of the string and matches the rest of the string while the second method matches the 5th element from the end of the string and ensures what follows the 5th element matches the pattern.
\S+
Match any non-whitespace character one or more times(?:\s+\S+){4}
Match the following exactly 4 times\s+
Match any whitespace characters one or more times\S+
Match any non-whitespace characters one or more times
\s*
Match any whitespace characters any number of times$
Assert position at the end of the line
Further explanations:
(\S+)
Captures any non-whitespace character one or more times into a capture group(?= ... )
where...
represents some pattern (in our case(?:\s+\S+){4}\s*$
). This is a positive lookahead that ensures what follows matches without consuming any characters.