Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building dynamic Regex in C# [duplicate]

Tags:

c#

regex

I use dynamically built regex. Problem is when symbol = "aaaa (1)" because regex tries to parse it, but I want to treat it literary

Regex regex = new Regex(@"(^" + "/(" + symbol + @" \(\d+\)$)|" + symbol);
like image 523
cargt3 Avatar asked Jan 17 '26 03:01

cargt3


1 Answers

You need to escape special chars:

var escapedSymbol = Regex.Escape(symbol);
Regex regex = new Regex(@"(^" + "/(" + escapedSymbol  + @" \(\d+\)$)|" + escapedSymbol );

Reffer: msdn

like image 104
pwas Avatar answered Jan 19 '26 17:01

pwas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!