簡體   English   中英

C#中的正則表達式問題僅返回單個匹配項

[英]Problems with regex in c# only returning a single match

我正在建立一個正則表達式,但缺少一些東西,因為它無法正常工作。 我的正則表達式邏輯試圖查找具有# anychars #的任何內容,並返回句子中匹配的數量,而不是單個匹配。 這里有一些例子

1- #_Title_# and #_Content_#應該返回兩個匹配項: #_Title_# and #_Content_#

2- Product #_TemplateName_# #_Full_Product_Name_# more text. text text #_Short_Description_# Product #_TemplateName_# #_Full_Product_Name_# more text. text text #_Short_Description_#應該返回3場比賽: #_TemplateName_# #_Full_Product_Name_##_Short_Description_#

等等。 這是我的正則表達式: ^(.*#_.*_#.*)+$

對我在做什么錯有任何想法嗎?

像這樣簡單:

#.*?#

要么:

#_.*?_#

如果您也嘗試匹配下划線(問題的原始版本尚不清楚)。 要么:

#_(.*?)_#

這樣可以更輕松地將#__#分隔符之間的標記作為組提取。

應該管用。 *? 是關鍵。 不是貪婪的 否則,您將匹配第一個和最后一個#之間的所有內容

因此,例如:

var str = "Product #_TemplateName_# #_Full_Product_Name_# more text. text text #_Short_Description_#";

var r = new Regex("#_(.*?)_#");

foreach (Match m in r.Matches(str)) 
{
    Console.WriteLine(m.Value + "\t" + m.Groups[1].Value);
}

輸出:

#_TemplateName_#         TemplateName
#_Full_Product_Name_#    Full_Product_Name
#_Short_Description_#    Short_Description

嘗試這個 :

            string[] inputs = {
                                  "#Title# and #Content#",
                                  "Product #TemplateName# #_Full_Product_Name_# more text. text text #_Short_Description_#"
                              };

            string pattern = "(?'string'#[^#]+#)";

            foreach (string input in inputs)
            {
                MatchCollection matches = Regex.Matches(input, pattern);
                Console.WriteLine(string.Join(",",matches.Cast<Match>().Select(x => x.Groups["string"].Value).ToArray()));
            }
            Console.ReadLine();

您的正則表達式不正確。 另外,如果要所有匹配,則要遍歷匹配。

static void Main(string[] args)
{
    string input = "Product #_TemplateName_# #_Full_Product_Name_# more text. text text #_Short_Description_#",
        pattern = "#_[a-zA-Z_]*_#";
    Match match = Regex.Match(input, pattern);
    while (match.Success)
    {
        Console.WriteLine(match.Value);
        match = match.NextMatch();
    }
    Console.ReadLine();
}

結果

在此處輸入圖片說明

不要使用錨並將正則表達式更改為:

(#[^#]+#)

在正則表達式中, [^#]表達式表示任何字符,但#

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"(#[^#]+#)";
      Regex rgx = new Regex(pattern);
      string sentence = "#blah blah# asdfasdfaf #somethingelse#";

      foreach (Match match in rgx.Matches(sentence))
     Console.WriteLine("Found '{0}' at position {1}", 
               match.Value, match.Index);
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM