I want to do some regex.match by building the pattern dynamically. The following code is not working. I was wondering how can I convert the string “^[ABCDEFG][ABCDEFG]$” to @”^[ABCDEFG][ABCDEFG]$” and use it for regex.
Thanks
static string Convert(string s)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
if (s[i].Equals('N'))
{
sb.Append("[ABCDEFG]");
}
else
{
sb.Append(s[i]);
}
}
return sb.ToString();
}
static void Main(string[] args)
{
string seq = "CA";
Regex re = new Regex(Convert("^NN$"));
if (re.Match(seq).Success)
{
Console.WriteLine("match");
}
Console.ReadKey();
}
A verbatim string (string literal prefixed with a
@) is only sytactic sugar to allow simpler file system access and regular expression writing, because in verbatim strings the character\isn’t treated as an escape character. That way you don’t have to write"\\\\\\.\\\\"to match the string"\.\"in a regex but only@"\\\.\\"which is less prone to error because counting the backslashes becomes easier as their number decreases.The following example will prove that verbatim strings are no different from normal ones: