2013-04-21 27 views
1

當我執行此代碼時,我得到了一些有趣的結果。

string readText = File.ReadAllText("d:\\temp.txt"); 
    Console.WriteLine(readText); 

    Console.WriteLine("From File: "+Regex.Matches(readText,"$").Count);//-->2 

    Console.WriteLine("Add \\n to the File: "+Regex.Matches(readText + "\n", "$").Count);//--->2 
    Console.WriteLine("Add multiple \\n to the file: "+Regex.Matches(readText + "\n\n\n", "$").Count);//--->2 

    Console.WriteLine("on Text \"sample\": "+Regex.Matches("sample", "$").Count);//--->1 
    Console.WriteLine("on Text \"sample\\n\\n\\n\": "+Regex.Matches("sample" + "\n\n\n", "$").Count);//--->2 

輸出:

First line 

third 


Line 6 
Line 7 

From File: 2 
Add \n to the File: 2 
Add multiple \n to the file: 2 
on Text "sample": 1 
on Text "sample\n\n\n": 2 

爲什麼它給我造成這個樣子。可以任何一個前飛機?在two possible positions

回答

1

$匹配:(滾動到部分「字符串帶有換行符結束」)之前的最後

  1. 在輸入字符串
  2. 在該位置的端如果字符串以換行符結尾,則換行爲字符串。

因此,如果您的字符串以一個或多個換行符結尾,則會爲$獲得兩個匹配項。在其他情況下,你會得到一個。

如果您只想匹配非常結尾的字符串,請改爲使用\z

在Python的實驗:

>>> [match.start() for match in re.finditer("$", "hello")] 
[5] 
>>> [match.start() for match in re.finditer("$", "hello\n")] 
[5, 6] 
>>> [match.start() for match in re.finditer("$", "hello\n\n")] 
[6, 7] 
>>> [match.start() for match in re.finditer("$", "hello\n\n\n")] 
[7, 8] 
+1

感謝:-)我需要先讀基礎 – Civa 2013-04-21 10:34:55

相關問題