Regex在.net中不能正常工作
本文关键字:工作 常工作 net 不能 Regex | 更新日期: 2023-09-27 18:14:15
我试图替换c#文件中的一些换行符,给定一个特定的模式:
(?m)(^'t[0-9A-Z#].+$)'r?'n
文件结构示例
1 1 1 1
ab as as
123 1 2
13
32 3 12 2
ds ds 12
应用$1't
作为替换,我期望得到以下结果:
1 1 1 1 ab as as
123 1 2 13
32 3 12 2 ds ds 12
实际上,这个替换在regexr中工作正常。
但是在c#中,文件只是返回不匹配项。这个。net匹配的正则表达式有什么特别之处吗?
public void masterDataEleb()
{
// Tried both with (?m) and RegexOptions.Multiline, not working
Regex masterDataRegex = new Regex(@"(^'t[0-9A-Z#].+$)'r?'n", RegexOptions.Multiline);
string replaceTo = "$1't";
string textFile = File.ReadAllText(filePath, Encoding.Default);
textFile = masterDataRegex.Replace(textFile, replaceTo);
File.WriteAllText(filePath, textFile, Encoding.Default);
}
在表达式的末尾(忽略捕获组),有如下序列:
$'r?'n
当你使用RegexOptions。在。net中,$
锚点贪婪地匹配LF
。您的匹配失败,因为您的文件中没有LFCRLF
或LFLF
序列。
您应该尝试使用模式'r?$
来匹配您的行尾。
您的模式在regexr中工作的原因可能是$
锚的行为不同(例如,regexr中的行为似乎与LF之前的$
匹配,尽管我怀疑由于类似的原因,以CRLF结尾的输入行可能会失败)。
这可能对您有所帮助。代入$1't$2$3
([^'r'n]*)'r?'n([^'r'n]*)('r?'n?)
在线演示 模式说明:
([^'r'n]*) Group everything till new line is found
'r?'n New line is found
([^'r'n]*) Group everything till new line is found
('r?'n?) New line is found(optional)