代码之家  ›  专栏  ›  技术社区  ›  Seattle Leonard

正则表达式C#问题

  •  6
  • Seattle Leonard  · 技术社区  · 14 年前

    我相信有一个简单的解决办法,但我似乎错过了。

    我需要一个正则表达式来执行以下操作:

    asdf.txt;qwer asdf.txt

    "as;df.txt";qwer 应该匹配 as;df.txt

    我的regex口味是C#。

    谢谢你的帮助!

    5 回复  |  直到 14 年前
        1
  •  2
  •   Doug Domeny    14 年前
    "[^"]+"(?=;)|[^;]+(?=;)
    

    这将匹配双引号中后跟分号的文本或后跟分号的文本。分号不包含在匹配项中。

    编辑:我意识到我的第一次尝试将符合报价。以下表达式将排除引号,但使用子表达式。

    "([^"]+)";|([^;]+);
    
        2
  •  1
  •   OmnipotentEntity    14 年前

    你应该这样做:

    (".*"|.*);
    

    它在技术上也与分号匹配,但是您可以将其切掉,或者只使用backreference(如果C支持backreference)

        3
  •  1
  •   Samuel Neff    14 年前

    这将匹配到 ; ;

    ("[^"]+";|[^;]+;)
    
        4
  •  0
  •   Dustin Laine    14 年前

    是否需要使用regex,您可以只使用C#string方法,它包含:

    string s = "asdf.txt;qwer";
    string s1 = "\"as;df.txt\";qwer";
    
    return s.Contains("asdf.txt"); //returns true
    return s1.Contains("\"as;df.txt\""); //returns true
    
        5
  •  0
  •   Doug    14 年前

    Matches matches = Regex.Matches('asdf.txt;qwer',"asdf.txt");
    

    Matches matches = Regex.Matches('"as;df.txt";qwer',"as;df.txt");