代码之家  ›  专栏  ›  技术社区  ›  C Bauer

Regex不在.NET中工作

  •  2
  • C Bauer  · 技术社区  · 15 年前

    所以我在试着配一个雷吉士,我在这方面还比较新。我使用了一个验证器,当我粘贴代码时,它会工作,但当它被放置在.net2.0c页的codebehind中时,它不会工作。

    有问题的代码应该能够在单个分号上拆分,但不能在双分号上拆分。但是,当我使用字符串时

    “条目;条目2;条目3;条目4;”

    我得到一个无意义的数组,其中包含空值、前一个条目的最后一个字母以及分号本身。在线的javascript验证器正确地分割它。请帮助!

    我的正则表达式:

    ((;;|[^;])+)
    
    3 回复  |  直到 15 年前
        1
  •  5
  •   Greg Bacon    15 年前

    拆分以下正则表达式:

    (?<!;);(?!;)
    

    它意味着匹配既没有前面也没有后面的分号的分号。

    例如,此代码

    var input = "entry;entry2;entry3;entry4;";
    foreach (var s in Regex.Split(input, @"(?<!;);(?!;)"))
        Console.WriteLine("[{0}]", s);
    

    生成以下输出:

    [entry]
    [entry2]
    [entry3]
    [entry4]
    []

    最后一个空字段是输入末尾分号的结果。

    如果分号是 终止符 在每个字段的末尾,而不是在连续字段之间使用分隔符,然后使用 Regex.Matches 相反

    foreach (Match m in Regex.Matches(input, @"(.+?)(?<!;);(?!;)"))
        Console.WriteLine("[{0}]", m.Groups[1].Value);
    

    得到

    [entry]
    [entry2]
    [entry3]
    [entry4]
        2
  •  1
  •   t0mm13b    15 年前

    为什么不使用 String.Split 在分号上?

    string sInput = "Entry1;entry2;entry3;entry4";
    string[] sEntries = sInput.Split(';');
    // Do what you have to do with the entries in the array...
    

    希望这有帮助, 最好的问候, 汤姆。

        3
  •  1
  •   nemke Todd Stout    15 年前

    正如Tommieb75所写,您可以使用 String.Split 具有 StringSplitOptions 枚举,以便控制新创建的拆分数组的输出

    string input = "entry1;;entry2;;;entry3;entry4;;";
    char[] charSeparators = new char[] {';'};
    // Split a string delimited by characters and return all non-empty elements.
    result = input.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
    

    结果将只包含以下4个元素:

    <entry1><entry2><entry3><entry4>