string line = "ena";
// pattern == "\\ENABLED"; pattern is input by user (see comments below)
string pattern = Console.ReadLine();
foreach (Match match in Regex.Matches(line, pattern,RegexOptions.CultureInvariant))
{
Console.WriteLine("match");
}
在上面的示例Regex.Matches()
类给予异常中,解析"\ENABLED"
-
无法识别的转义序列\ E。
答案 0 :(得分:1)
例外的直接原因是正则表达式和 C#将反斜杠(\
)视为< em>特殊符号,例如
\bABC\p{L}
两个\
的模式都有特殊含义。因此,您必须转义\
两次(对于C#和正则表达式):
const string pattern = "\\\\ENABLED";
或者(为了使pattern
更具可读性),您可以将字符串逐字逐句地输入:
const string pattern = @"\\ENABLED";
如果是用户(请参阅问题注释)谁提供了模式,我们应该准备好获得一个在语法上不正确的;我们可以尝试捕获异常:
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
}
如果pattern
中提供了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
}