代码之家  ›  专栏  ›  技术社区  ›  Shane Castle

偷偷摸摸的反斜杠-regex的情况

  •  1
  • Shane Castle  · 技术社区  · 14 年前

    我错过了一些很明显的东西,但我就是看不见。

    我已经得到:

    string input = @"999\abc.txt";
    string pattern = @"\\(.*)";
    string output = Regex.Match(input,pattern).ToString();
    Console.WriteLine(output);
    

    我的结果是:

    \abc.txt
    

    我不想要斜线 也不明白它为什么会潜入输出。我尝试翻转模式,斜线再次卷进输出:

    string pattern = @"^(.*)\\";
    

    得到:

    999\
    

    奇怪。结果在Osherove的调节器中很好。有什么想法吗?

    谢谢。

    5 回复  |  直到 14 年前
        1
  •  10
  •   Marc Gravell    14 年前

    这个 Match 整个的 匹配;你想要第一组;

    string output = Regex.Match(input,pattern).Groups[1].Value;
    

    (根据记忆;可能略有不同)

        2
  •  1
  •   Mark Byers    14 年前

    使用 Groups 只获取组,而不是整个匹配:

    string output = Regex.Match(input, pattern).Groups[1].Value;
    
        3
  •  0
  •   Amber    14 年前
        4
  •  0
  •   Thomas Levesque    14 年前

    作为Marc答案的替代方案,您可以使用 zero-width positive lookbehind assertion 按照您的模式:

    string pattern = @"(?<=\\)(.*)";
    

    这将与“\”匹配,但将其从捕获中排除

        5
  •  0
  •   csharptest.net    14 年前

    您可以尝试匹配前缀/后缀,但排除选项。

    匹配第一个斜线后的所有内容/

    (?<=\\)(.*)$
    

    匹配最后一个斜线后的所有内容/

    (?<=\\)([^\\]*)$
    

    匹配最后一个斜线前的所有内容/

    ^(.*)(?=\\)
    

    顺便说一下,下载 Expresso 对于测试正则表达式,总的生命节省。