Splunk Search

rex stop after first match

poisar
Explorer

i have a field with several strings like

fieldname = AT-field2-field3

fieldname = DE-field2

fieldname = DE-field2-field3-field4

etc...

 

I try to get a rex to just get the country code:

|rex field=fieldname "^(?<country>.*)-.*"

 

but the result is not just the  Country Code

 

any ideas?

Labels (2)
0 Karma
1 Solution

richgalloway
SplunkTrust
SplunkTrust

The .* operator is greedy so it will grab as many characters as it can that still match the expression.  One solution is to use the non-greedy quantifier.

|rex field=fieldname "^(?<country>.*?)-.*"

Another solution is to take everything up to the first hyphen.  Like this:

| rex field=fieldname "^(?<country>[^-]+)-"

 

---
If this reply helps you, Karma would be appreciated.

View solution in original post

richgalloway
SplunkTrust
SplunkTrust

The .* operator is greedy so it will grab as many characters as it can that still match the expression.  One solution is to use the non-greedy quantifier.

|rex field=fieldname "^(?<country>.*?)-.*"

Another solution is to take everything up to the first hyphen.  Like this:

| rex field=fieldname "^(?<country>[^-]+)-"

 

---
If this reply helps you, Karma would be appreciated.

poisar
Explorer

thank you for your input. Both variants work and i learned something new 🙂

0 Karma
Get Updates on the Splunk Community!

Index This | What’s a riddle wrapped in an enigma?

September 2025 Edition Hayyy Splunk Education Enthusiasts and the Eternally Curious!  We’re back with this ...

BORE at .conf25

Boss Of Regular Expression (BORE) was an interactive session run again this year at .conf25 by the brilliant ...

OpenTelemetry for Legacy Apps? Yes, You Can!

This article is a follow-up to my previous article posted on the OpenTelemetry Blog, "Your Critical Legacy App ...