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!

Fall Into Learning with New Splunk Education Courses

Every month, Splunk Education releases new courses to help you branch out, strengthen your data science roots, ...

Super Optimize your Splunk Stats Searches: Unlocking the Power of tstats, TERM, and ...

By Martin Hettervik, Senior Consultant and Team Leader at Accelerate at Iver, Splunk MVPThe stats command is ...

How Splunk Observability Cloud Prevented a Major Payment Crisis in Minutes

Your bank's payment processing system is humming along during a busy afternoon, handling millions in hourly ...