2011-10-08 87 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选项 - 您可能必须调整表情,但会为您搜索“向后”。