代码之家  ›  专栏  ›  技术社区  ›  Furquan Khan

使用C中的regex提取某些子字符串#

  •  1
  • Furquan Khan  · 技术社区  · 7 年前

    我有一个词有一段话要说 1.2.2 和A some text 然后 some other texts . 我想去拿那部分。我创建了一个regex来匹配部分和一些文本。

    以下是我的代码:

    var word = "1.2.3 area consent testing, sklfjsdlkf jdifgjds visjeflk area consent testing lsdajfgo idsjgosa jfikdjfl343 fjdsl45jl sfgjsoiaetj l area consent testing";
    var lowerWord = "area consent testing".ToLower();
    var textLower = @word.ToLower().ToString();
    Dictionary<int, string> matchRegex = new Dictionary<int, string>();
    matchRegex.Add(1, @"(^\d.+(?:\.\d+)*[ \t](" + lowerWord + "))"); 
    
    
    foreach (var check in matchRegex)
    {
        string AllowedChars = check.Value;
        Regex regex = new Regex(AllowedChars);
        var match = regex.Match(textLower);
        if (match.Success)
        {
            var sectionVal = match.Value;
        }
    }
    

    现在我的问题是,我只想要价值 1.2.3 area consent testing 在我的 sectionVal 变量,但它给了我整条线。 即

    sectionVal = "1.2.3 area consent testing, sklfjsdlkf jdifgjds visjeflk area consent testing lsdajfgo idsjgosa jfikdjfl343 fjdsl45jl sfgjsoiaetj l area consent testing";
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Titian Cernicova-Dragomir    7 年前

    regex的开头包含一个未捕获的 . 它将匹配任何字符和 + 之后。试试这个:

    @"^(\d+(\.\d+)*[ \t](" + lowerWord + "))"