The rex or regular expression command is extremely useful when you need to extract a field during search time that has not already been extracted automatically. The rex command even works in multi-line events. The following sample command will get all versions of the Chrome browser that are defined in the highlighted user agent string part of the raw data. Let's say this is your raw data, and you need to get the highlighted value:
016-07-21 23:58:50:227303,96.32.0.0,GET,/destination/LAX/details,-,80, -,10.2.1.33,Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML; like Gecko) Chrome/29.0.1547.76 Safari/537.36,500,0,0,823,3053
You can use this search command to get it:
SPL> index=main | rex field=http_user_agent "Chrome/(?<Chrome_Version>.+?)?Safari" | top Chrome_Version
The rex command extracted a field called Chrome_Version during the search and made it available for all succeeding commands. The results are shown in the following screenshot:
Tip from the Fez: While Splunk allows the rex command in SPL, it is generally a best practice—once you're sure that the rex command is accurate for your situation—to create a Splunk field extraction so that the regular expression logic can be stored in one place and reused in searches like any other field.