代码之家  ›  专栏  ›  技术社区  ›  James King

正则表达式:匹配到可选单词

  •  6
  • James King  · 技术社区  · 14 年前

    需要匹配句子的第一部分,直到给定的单词。但是,这个词是可选的,在这种情况下,我想匹配整个句子。例如:

    我有一个句子里有一个我不想要的从句。

    我有一个句子,我喜欢它。

    在第一种情况下,我想 "I have a sentence" . 在第二种情况下,我想 "I have a sentence and I like it."

    环顾四周会给我第一种情况,但一旦我试图让它可选,涵盖第二种情况,我得到了整个第一句话。我试着让这个表达变得懒惰。。。没有骰子。

    适用于第一种情况的代码:

    var regEx = new Regex(@".*(?=with)");
    string matchstr = @"I have a sentence with a clause I don't want";
    
    if (regEx.IsMatch(matchstr)) {
        Console.WriteLine(regEx.Match(matchstr).Captures[0].Value);
        Console.WriteLine("Matched!");
    }
    else {
        Console.WriteLine("Not Matched : (");
    }
    

    var regEx = new Regex(@".*(?=with)?");
    


    有什么建议吗?

    提前谢谢!
    詹姆斯

    3 回复  |  直到 14 年前
        1
  •  11
  •   Community Nick Dandoulakis    7 年前

    有几种方法可以做到这一点。你可以这样做:

    ^(.*?)(with|$)
    

    with 或者在队伍的尽头 $ anchor .

    I have a sentence with a clause I don't want.
    I have a sentence and I like it.
    

    as seen on rubular.com ):

      • 第1组: "I have a sentence "
      • 第2组: "with"
      • 第1组: "I have a sentence and I like it" .
      • "" (空字符串)

    您可以使用 (?:with|$) 如果你不需要区分这两种情况。

    相关问题

        2
  •  1
  •   zigdon    14 年前

    如果我正确理解你的需要,你想把句子和单词“with”匹配起来,或者,如果没有,把整个句子都匹配起来?为什么不编写regexp来显式地查找这两种情况呢?

    /(.*) with |(.*)/
    

    这不是两个案子都有吗?

        3
  •  1
  •   LukeH    14 年前
    string optional = "with a clause I don't want" 
    string rx = "^(.*?)" + Regex.Escape(optional) + ".*$";
    
    // displays "I have a sentence"
    string foo = "I have a sentence with a clause I don't want.";
    Console.WriteLine(Regex.Replace(foo, rx, "$1"));
    
    // displays "I have a sentence and I like it."
    string bar = "I have a sentence and I like it.";
    Console.WriteLine(Regex.Replace(bar, rx, "$1"))
    

    如果您不需要regex提供的复杂匹配,那么可以使用 IndexOf Remove . (显然,您可以将逻辑抽象为助手和/或扩展方法或类似方法):

    string optional = "with a clause I don't want" 
    
    // displays "I have a sentence"
    string foo = "I have a sentence with a clause I don't want.";
    int idxFoo = foo.IndexOf(optional);
    Console.WriteLine(idxFoo < 0 ? foo : foo.Remove(idxFoo));
    
    // displays "I have a sentence and I like it."
    string bar = "I have a sentence and I like it.";
    int idxBar = bar.IndexOf(optional);
    Console.WriteLine(idxBar < 0 ? bar : bar.Remove(idxBar));