此问题在此处已有答案:
Escape Special Character in Regex(3个答案)
17天前关闭。
我使用了一个代码,在一组文件中搜索多个字符串,它工作得很好,直到我在其中一个搜索字符串中包含管道字符。
这是我一直在使用的,不知道如何修改它接受管道字符作为搜索的一部分。
这里的“fi”是我正在搜索的当前文件的FileInfo变量,searchStr是一个包含我正在搜索的字符串的数组。
foreach (var line in Extensions.WriteSafeReadAllLines(fi.FullName)) // This method fixes the issue of reading lines when file is open.
{
// Escape "|" character in search strings
SearchStr = SearchStr.Select(l => l.Replace("|", @"\|")).ToArray();
string pattern = string.Join("|", SearchStr); // <-- what if one of the search strings has '|'
MatchCollection matches = Regex.Matches(line, pattern, RegexOptions.Multiline);
foreach (Match match in matches)
{
string theEntireLine = match.Groups[0].Value;
// do whatever with the line that contains any of the search strings
}
}
字符串
正在搜索的文件中的采样行:
2023-10-31 00:34:31:162|2023-10-31 00:34:31:162,[1.23.4:12870],ABC,XX,102,128001dLV816409130 RLCAYV0B 1M0 20231025152123 },
2023-10-31 00:34:58:940|2023-10-31 00:34:58:940,[1.23.4:12870],XX,ABC,60,d128101LZ240126628 },
2023-10-31 00:34:59:268|2023-10-31 00:34:59:268,[1.23.4:12870],ABC,X,102,128101dLZ240126628 RLCAYT2R0W8 20231028060553 },
型
搜索这些字符串,作为文本区域的输入,每行搜索一个字符串
00:34:31:162|2023-10-31
128101dLZ240126628
型
SearchStr数组现在包含:
"00:34:31:162\\|2023-10-31"
"128101dLZ240126628"
型
它匹配包含“2023-10-31”的每一行,即使这样,它也不会返回整行,而是返回“2023-10-31”
如果我按照Nick的建议使用RegEx.Escape,“pattern”将如下所示:
\\|00:34:31:162\\|2023-10-31|128101dLZ240126628
型
1条答案
按热度按时间vkc1a9a21#
如果我对你的问题理解正确的话,首先,将模式创建移动到循环之外,否则你将在循环的每次迭代中对模式进行多重转义。
第二,听起来你想要整行,只要一行匹配任何搜索字符串。为此,你只需要在for循环中引用
line
变量:字符串