Filter Variable to Escape Regular Expression Special Characters

Is there any way to filter Variable to escape RegEx special characters?

1 Like

I think this will work:

Here's the regular expression:

([.*+?^=!:${}()|\[\]\/\\])

And here's the replace string:

[Moderator's Edit: It should be TWO backslashes instead of three:]

\\$1
1 Like

Dan, always to the rescue! I searched the forum and this was exactly what I was looking for. It worked for me, but with the replace string as 2 slashes instead of 3:

\\$1

It was also cool to learn from this that when wrapped in [square brackets], only a handful of these special characters need to be escaped with the preceding \ rather than needing to do them all: \. \* \+ \? etc

Thanks for posting this!

2 Likes

So I have been trying the above and it doesnt work for me.

I have variables with text in it, the text often has what are regular expression escape characters in them, like "+" "=" "(" and ")".

If my text/variable doesnt have these characters, my macro's regular expression search/replace commands work great! If they do have those characters, my macro breaks.

I need to perform regular expression search/replace functions on these variables but without getting rid of those special characters as they are important text.

What is the best way to handle this? My brute force thought is to first convert the text to have easy to identify tags for the special characters. Like to do a non-regex find/replace for "(" and replace it with TAGLEFTPAREN. Do my regex operation. And then find/replace the TAGLEFTPAREN back with "(".

This seems highly inelegant, so I'm hoping there is an easier way to ask KM to auto-magically to do this.

Thanks for any help!

@DanThomas, I hope you don't mind that I fixed your REPLACE regex. If you disagree, please feel free to respond with correct change.

1 Like

No, that's perfect. Thanks!

1 Like

I tried this, expecting the result to include visibly escaped special characters, so either it doesn't work or I've misunderstood the aim.

Usage Example

Result

CleanShot 2022-08-21 at 09.24.48@2x|478x192, 50%, 70%

I expected the result to be:

These \(brackets\) should be escaped

Works fine for me:

KM 0 2022-08-21_10-34-07

Here's my Search and Replace action for you to try in case you've got a typo or something...

Search and Replace.kmactions (631 Bytes)

Well that's very odd. Yours is green, mine is red. Yours works, mine doesn't.

Screenshot

All's well that ends well. Thanks!

1 Like