【问题标题】:Get string between / and \ using Regular Expression使用正则表达式获取 / 和 \ 之间的字符串
【发布时间】:2018-03-18 07:19:33
【问题描述】:

请考虑这个字符串:

http://tempuri.org/IService1/GetData\

我想使用正则表达式获取GetData。我用这段代码测试它:

Regex regex = new Regex("\\/\\w*\\");

但我收到此错误:

System.ArgumentException: 'parsing "/\w*\" - Illegal \ at end of pattern.'

然后我测试这段代码:

Regex regex = new Regex(@"\/\w*\\");

但它不起作用并且无法识别任何匹配项。

我可以使用正则表达式在上面的字符串中识别GetData吗?

谢谢

【问题讨论】:

    标签: c# regex c#-4.0


    【解决方案1】:
    var input = @"http://tempuri.org/IService1/GetData\";
    Regex regex = new Regex(@"/(\w*)\\");
    var match = regex.Match(input);
    if (match.Success)
    {
        //  data = "GetData"
        var data = match.Groups[1].Value;
    }
    

    Regex("\\/\\w*\\") 在反斜杠后将结果转义为正则表达式 \/\w*\ 。此表达式不正确,因为尾部反斜杠。这会导致Illegal \ at end of pattern 错误。

    在 RE 中有这么多应该转义的反斜杠,很有可能会出错。这就是为什么在构建正则表达式时最好使用verbatim strings 的原因。与通常的 C# 字符串相同的正则表达式应构建为new Regex("/(\\w*)\\\\$")。最后那四个斜线简直要了我的命。

    【讨论】:

    • 谢谢,但您的模式无法识别 var input3 = "\"http://tempuri.org/IService1/GetData\""; 中的 GetData
    • 如果反斜杠不是输入字符串的最后一个字符,那么你应该从我原来的正则表达式中删除$。我已经编辑了答案。
    猜你喜欢
    • 1970-01-01
    • 2019-03-30
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 2017-07-16
    • 1970-01-01
    相关资源
    最近更新 更多