简体   繁体   中英

Problems with regex in c# only returning a single match

I'm building a regex and I'm missing something as it's not working properly. my regex logic is trying to look for anything that has # anychars # and return the number of matches on the sentence and not a single match. Here are a few examples

1- #_Title_# and #_Content_# should return two matches: #_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_# should return 3 matches: #_TemplateName_# #_Full_Product_Name_# and #_Short_Description_#

and so on. Here is what my regex looks like: ^(.*#_.*_#.*)+$

any thoughts on what I'm doing wrong?

Something as simple as:

#.*?#

Or:

#_.*?_#

If you are trying to match the underscores too (it wasn't clear in the original version of the question). Or:

#_(.*?)_#

Which makes it easier to extract the token between your #_ and _# delimiters as a group.

Should work. The *? is key. It's non-greedy . Otherwise you match everything between the first and last #

So for example:

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);
}

Outputs:

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

Try this :

            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();

You regular expression is not correct. In addition, you want to loop through match if you want all matching.

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();
}

Result

在此处输入图片说明

Don't use anchors and change your regex to:

(#[^#]+#)

In regex the [^#] expression means any character BUT #

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);
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM