Splunk Search

Is it is posible to use a variable in a regex of a field extraction ?



I would like to know if it is possible to use a variable in a regex extraction.
....| eval snr=602 | rex "(?<blabla> Step\s+snr)"

In this bad example (which doesn't work) the snr variable it is use in the regular expression for extracting the variable "blabla". The reason I need to this it is because I have a token value which is a string and I need to trim the leading zero of that value and then use it in a regex.

token_value="0602" (String format) - This value is obtain from another panel.

I need to trim the leading zero from this value and use it in a regular expression.

... | eval snr=ltrim($token$,"0") | rex "(?<blabla> Step\s+snr)"

If this is not possible it would very nice to add this functionality for future version . I am going to be working to find a way around this issue and I appreciate your help in this matter.

Esteemed Legend

There are 2 "templatizing" features in Splunk that will allow the tokenization of anything in SPL: the map command and subsearches. To see a very similar Q&A using map to tokenize regex, go here (you should be able to modify for your situation):


0 Karma

Splunk Employee
Splunk Employee

Splunk uses regex to define fields via capturing groups. Not the other way around. The regex syntax can only see what is actually in the text it's being compared to... so no, you can't insert a field with a specific value into your regex as a placeholder...

You could however, compare the two values once you've extracted the field you're calling "blabla".

That's your actual question... and it's worth posting a new question to get the variety of answers.

For instance, if you wanted to be clunky about it

 | eval snr=ltrim($token$,"0") | rex "(?<blabla> Step\s+\d{3})"|rex field=blabla " Steps\s+(?<eventSnr>\d{3}|...

now that both values are in Splunk fields... you can compare them, coalesce them, do whatever...

I'd repost as a question about comparing the two for whatever your end purpose is.

Bottom line... yes, regex actually has tokens and variables, but it's all about the text it's looking at, not an outside parameter...

With Splunk... the answer is always "YES!". It just might require more regex than you're prepared for!
0 Karma


Very interesting. Thanks for your input. I am trying to find a way around. I was thinking about writing an internal search that would get the token value and modify it using eval. Then I would pass this value to an internal input form as a token. And now I could pass the value directly to my regex. This is sure a very tedious process, but it would have the functionality I want.

I definitively would test your suggestion. I didn't know that was possible.

0 Karma


A similar question is here.

If this reply helps you, an upvote would be appreciated.
0 Karma