1

在以下代码中,为什么模式与正则表达式不匹配,但如果我使用正则表达式逐行读取 12sep.txt 文件,则它可以正常工作?

string file = @"C:\Documents and Settings\Sandeep.kumar\Desktop\12sep.txt";
string filedta = File.ReadAllText(file);
string pattern = @"^[^\s]+.[^\s]txt$";
Regex rx = new Regex(pattern, RegexOptions.None);
MatchCollection mc = rx.Matches(filedta);
4

1 回答 1

11

Regex special character "^" and "$" don't have the same meaning when the input string is single-line or multi-line. In single line the mean "string start" and "string end". In multi-line they mean "line start" and "line end".

You have a option in RegexOptions to control this : RegexOptions.Multiline

And the documentation clearly states what it does : "Multiline mode. Changes the meaning of ^ and $ so they match at the beginning and end, respectively, of any line, and not just the beginning and end of the entire string."

from http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regexoptions.aspx

于 2012-09-13T10:08:06.677 回答