c# – Variables in regular expressions

Question:

Gentlemen, reg template. expression consists of three parts – variable, reg. expression, variable, for example stringBefore + @"([\w]+)" + stringAfter .
Everything would be fine, but in addition to letters in stringAfter there is an opening parenthesis and Regex thinks that this is part of a regular expression, and therefore the error " No matching closing parentheses " is thrown.

How to make variables recognized as plain text?

Answer:

Use Regex.Escape() :

Converts the minimum character set ( \ , * , + , ? , | , { , [ , ( , ) , ^ , $ , . , # And space), replacing them with the appropriate escape codes. This instructs the regular expression engine to interpret these characters literally and not as metacharacters.

Example of a declaration:

var reg = new Regex($@"{Regex.Escape(stringBefore)}(\w+){Regex.Escape(stringAfter)}");

In older versions of C #, you can use a similar

var reg = new Regex(string.Format(@"{0}(\w+){1}", Regex.Escape(stringBefore), Regex.Escape(stringAfter)));
Scroll to Top