The immediate cause of the exception is that regular expressions as well as C# treat backslash (\
) as a special symbol, e.g. in the
\bABC\p{L}
pattern both \
have a special meaning. So you have to escape \
twice (for C# and for regex):
const string pattern = "\\\\ENABLED";
or (in order to make pattern
be more readable) you can turn string into verbatim one:
const string pattern = @"\\ENABLED";
If it's user (see comments to the question) who provides the pattern we should be ready to get a syntactically incorrect one; we can try catching exception(s):
Regex regex = null;
while (true) {
Console.WriteLine("Please, provide the pattern: ");
try {
// Try to get pattern from user
// Trim() - let's be nice and remove leading / trailing spaces
// TimeSpan.FromSeconds(10) - user can provide a very bad pattern,
// we don't want to freeze forever (10 seconds at most)
regex = new Regex(
Console.ReadLine().Trim(),
RegexOptions.CultureInvariant,
TimeSpan.FromSeconds(10));
// if pattern is syntactically valid
break;
}
catch (ArgumentException e) {
Console.WriteLine($"Pattern is invalid: {e.Message}");
}
}
// We have a valid Regex regex based on user pattern; let's use it:
try {
foreach (Match match in regex.Matches(line)) {
Console.WriteLine("match");
}
}
catch (RegexMatchTimeoutException) {
//TODO: pattern is bad one, let user know it
}
Same idea if pattern
is provided in a TextBox
:
Regex regex = null;
try {
regex = new Regex(
patternTextBox.Text.Trim(),
RegexOptions.CultureInvariant,
TimeSpan.FromSeconds(10));
}
catch (ArgumentException e) {
if (patternTextBox.CanFocus)
patternTextBox.Focus();
MessageBox.Show($"Incorrect pattern: {e.Message}");
return;
}
try {
foreach (Match match in regex.Matches(line)) {
...
}
}
catch (RegexMatchTimeoutException) {
//TODO: pattern is bad one, let user know it
}