2012-06-11 94 views
0

我有一个精确定义这样的字符串扩展:Regex.Match不工作正确

public static string GetStringBetween(this string value, string start, string end) 
{ 
    start = Regex.Escape(start); 
    end = Regex.Escape(end); 

    GroupCollection matches = Regex.Match(value, start + @"([^)]*)" + end).Groups; 

    return matches[1].Value; 
} 

但是,当我把这个:

string str = "The pre-inspection image A. Valderama (1).jpg of client Valderama is not..."; 
Console.WriteLine(str.GetStringBetween("pre-inspection image ", " of client")); 

它不写什么。但是,当str值是这样的:

string str = "The pre-inspection image A. Valderama.jpg of client Valderama is not..."; 

它工作正常。为什么会这样?

我的代码是C#,4框架,建立在VS2010专业版。

请帮忙。提前致谢。

回答

2

因为你指定要排除捕获组您正则表达式中的字符)[^)]@"([^)]*)"

而且由于)出现的第一个字符串:Valderama (1).jpg,它将不能够匹配。

你可能想@"(.*)"代替。

+0

我怎样才能改变,没有发生冲突的'('和')'符号?请帮忙。 –

+0

非常感谢。 :) –