Splunk Search

Splunk bug: string replace function fails if the string to be replaced starts with "+" character

Dev999
Communicator

replace() function produce an empty string if the string to be replaced starts with a "+" character.

this search with replace() works:

 

| makeresults 
| eval message = "This is mark1 replacement mark2", ph2="different" 
| rex field=message "mark1 (?<ph1>[^/s]*) mark2" 
| eval message2 = replace(message, ph1, ph2)
| table message, message2, ph1, ph2

 

Dev999_1-1676651078169.png

this one will produce an empty message2:

 

| makeresults 
| eval message = "This is mark1 +replacement mark2", ph2="different" 
| rex field=message "mark1 (?<ph1>[^/s]*) mark2" 
| eval message2 = replace(message, ph1, ph2)
| table message, message2, ph1, ph2

 

Dev999_0-1676651034277.png

Labels (1)
Tags (1)
0 Karma

ITWhisperer
SplunkTrust
SplunkTrust

The replace function treats the string to be replaced as a regex - "+" is a special character in regex and because it isn't preceded by anything, this makes the regex invalid, hence, it does perform as expected.

0 Karma

Dev999
Communicator

the function should have ways to escape the special characters. As you can see above, the extraction rex has no problem handling it.

0 Karma

ITWhisperer
SplunkTrust
SplunkTrust

The extraction works because the extracted string is not processed as a regex (until you put it in the replace function).

You could try something like this

 

| rex mode=sed field=ph1 "s/([\+\\\*\{\}\[\]\.\(\)\|\?])/#\#\1/g"
| rex mode=sed field=ph1 "s/#//g"
| eval message2 = replace(message, ph1, ph2)

 

0 Karma
Get Updates on the Splunk Community!

Stay Connected: Your Guide to May Tech Talks, Office Hours, and Webinars!

Take a look below to explore our upcoming Community Office Hours, Tech Talks, and Webinars this month. This ...

They're back! Join the SplunkTrust and MVP at .conf24

With our highly anticipated annual conference, .conf, comes the fez-wearers you can trust! The SplunkTrust, as ...

Enterprise Security Content Update (ESCU) | New Releases

Last month, the Splunk Threat Research Team had two releases of new security content via the Enterprise ...