【问题标题】:Regex.Match doesnt work correctlyRegex.Match 无法正常工作
【发布时间】:2012-06-11 18:11:26
【问题描述】:

我有一个字符串扩展,它的定义完全像这样:

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 Pro 中构建。

请帮忙。提前致谢。

【问题讨论】:

    标签: c# regex .net-4.0


    【解决方案1】:

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

    而且由于)出现在第一个字符串:Valderama (1).jpg中,所以无法匹配。

    你可能想要@"(.*)"

    【讨论】:

    • 如何在不与() 符号冲突的情况下更改它?请帮忙。
    猜你喜欢
    • 2016-12-01
    • 1970-01-01
    • 2016-09-01
    • 2012-07-11
    • 2018-04-08
    • 2017-04-20
    • 2018-10-02
    • 2016-09-04
    • 2010-10-06
    相关资源
    最近更新 更多