Splunk Search

How to escape a parenthesis when using rex to create a field?

Splunkster45
Communicator

I have a question about extracting two fields from the below sample text

Session <number> (<username>@<ipaddress>) started

I would like to be able to store the variable number and username as a field, but I am running into issues with the '('. Whenever I run the command, I get an error message saying that I am missing a ')'

Here is the command that I am using

| rex field=_raw "Session (?<number><backslash>w+) ((?<username><backslash>w+)@"

The number is either a 4 or 5 digit number and the username is always 6 characters. I do not care about the IP address.

How can I escape the parenthesis? I've done a little bit of searching and found a question that asked about escaping a '(' in a macro, but either that didn't apply or I couldn't follow it.

Thanks in advance!

Tags (3)
0 Karma
1 Solution

jrodman
Splunk Employee
Splunk Employee

In PCRE regexes (which Splunk uses), punctuation preceded by a backslash always matches the punctuation, so \( matches a (.
Parens without a backslash form groups as you are using to find your number. There is a bit of a trick though, because the search language also uses backslashes for escaping. Therefore I would suggest

 | rex field=_raw "Session (?<number>\\w+) (?<username>\\(\\w+)@"

View solution in original post

jrodman
Splunk Employee
Splunk Employee

In PCRE regexes (which Splunk uses), punctuation preceded by a backslash always matches the punctuation, so \( matches a (.
Parens without a backslash form groups as you are using to find your number. There is a bit of a trick though, because the search language also uses backslashes for escaping. Therefore I would suggest

 | rex field=_raw "Session (?<number>\\w+) (?<username>\\(\\w+)@"

Splunkster45
Communicator

Thanks! I modified your search command to the following and it worked perfectly

| rex field=_raw "Session (?\\w+) \\((?\\w+)@"

jrodman
Splunk Employee
Splunk Employee

Ah, seems I slightly misunderstood the goal. In retrospect it should have been obvious. Glad it's working.

0 Karma
Career Survey
First 500 qualified respondents will receive a $20 gift card! Tell us about your professional Splunk journey.
Get Updates on the Splunk Community!

Tech Talk Recap | Mastering Threat Hunting

Mastering Threat HuntingDive into the world of threat hunting, exploring the key differences between ...

Observability for AI Applications: Troubleshooting Latency

If you’re working with proprietary company data, you’re probably going to have a locally hosted LLM or many ...

Splunk AI Assistant for SPL vs. ChatGPT: Which One is Better?

In the age of AI, every tool promises to make our lives easier. From summarizing content to writing code, ...