Splunk Search

How do you use regex to escape a backslash?

jacqu3sy
Path Finder

Hi,

I have the following regex which works on regex101, but gives me an error when I try and use this within a Splunk query. Not sure if it's the fact that Im trying to escape the backslash that's causing the issue.

I have the field;

"UserName\a123456"

And I want to extract this into a field called NewUserName where it equals everything after the \ and up to closing quotes. So

NewUserName should be;

a123456

As I said, it works on Regex101 with the following;

"ADMIN\\*(?P[^"]*)"

But when I try it in Splunk via;

| rex field=_raw "ADMIN\\*(?P[^"]*)"

I get the error;

Mismatched ']' 

Any ideas?

0 Karma
1 Solution

vnravikumar
Champion

Hi @jacqu3sy

Try this

| makeresults 
   | eval msg="UserName\a123456" | rex field=msg "\\\(?P<NewUserName>.*)"

View solution in original post

kushagra9120
Explorer

I think this should work as it will only pick the string in format "UserName\a123456" and not any string that starts with backslash :-

rex field =_raw "^".\(?P.)\""

0 Karma

mydog8it
Builder

I don't see your regex working in regex101 with the sample provided. This regex matches your sample in regex101...
UserName\(?P[^"]*)

so perhaps this would work in Splunk...
rex field=_raw "UserName\(?P[^"]*)"

0 Karma

vnravikumar
Champion

Hi @jacqu3sy

Try this

| makeresults 
   | eval msg="UserName\a123456" | rex field=msg "\\\(?P<NewUserName>.*)"

Ganesh_Udar
Engager

Great , ! Thank you so much.

0 Karma

jacqu3sy
Path Finder

Thanks. That worked. Not sure why it needs 3 backslashes though?! Think thats what caught me out. And could you explain what the P after the ? is for?

Thanks.

0 Karma

vnravikumar
Champion

(?P<>) is a named group which stores the extracted value.

0 Karma

woodcock
Esteemed Legend

The P is not necessary in Splunk's implementation of RegEx, but it is harmless (and distracting). I never use it.

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, ...