2011-10-08 85 views
3

我有這樣的片段執行正則表達式搜索:正則表達式:反轉匹配順序

public IEnumerable<MyMatch> GetMyMatches() 
{ 
    Match m = myRegex.Match(Text, offset); 
    if (m != null && m.Success && m.Value != null && m.Value.Length > 0) 
    { 
     offset = m.Index+m.Length; 
     yield return new MyMatch() { Match=m, SomeFurtherInformation=... }; 
    } else 
    yield break; 
} 

正如你所看到的,我走所有occourences在我的文字。

但如何反轉搜索方向?

感謝您的幫助

+1

注意:m!= null始終爲真,m.Value!= null也是如此,除非有例外(比如偏移量太大)但是沒有m :-)如果沒有匹配,則Value = =「」。 – xanatos

回答

5

你可以使用「Matches」然後做對返回IEnumerable的一個「Reverse」。

+1

+1,'Matches'保證在零長度匹配的情況下不會遇到無限循環(請參閱http://msdn.microsoft.com/zh-cn/library/h9ee7wwd.aspx上的註釋),與您當前的代碼相反。 –

2

RegexOptions有一個RightToLeft選項 - 您可能必須調整表情,但會爲您搜索「向後」。