Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add prefix to special characters with Regular Expressions

Tags:

c#

regex

I have a list of special characters that includes ^ $ ( ) % . [ ] * + - ?. I want put % in front of this special characters in a string value.

I need this to generate a Lua script to use in Redis.

For example Test$String? must be change to Test%$String%?.

Is there any way to do this with regular expressions in C#?

like image 851
Fred Avatar asked Feb 07 '23 00:02

Fred


2 Answers

In C#, you just need a Regex.Replace:

var LuaEscapedString = Regex.Replace(input, @"[][$^()%.*+?-]", "%$&");

See the regex demo

The [][$^()%.*+?-] character class will match a single character, either a ], [, $, ^, (, ), %, ., *, +, ? or - and will reinsert it back with the $& backreference in the replacement pattern pre-pending with a % character.

A lookahead is just a redundant overhead here (or a show-off trick for your boss).

like image 56
Wiktor Stribiżew Avatar answered May 12 '23 05:05

Wiktor Stribiżew


You can use lookaheads and replace with %

/(?=[]*+$?)[(.-])/

Regex Demo

  • (?=[]*+$?)[(.-]) Postive lookahead, checks if the character following any one from the altenation []. If yes, substitutes with %
like image 29
nu11p01n73R Avatar answered May 12 '23 06:05

nu11p01n73R