Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find which subpattern matched in regex

Tags:

c#

regex

Is it possible via regex find which sub pattern match in string, suppose we want check that "2D3" via "\d{1,}D{1,}".

string pattern  = "\d{1,}D\d{1,}";
string str = "2D3";
var r = new Regex(pattern)
if(r.IsMatch(str))
{
   Dictionary<string, string> Out = new Dictionary<string, string>();
   //Some Code Here???
   Log(Out);
}

/////////////Out Must Be/////////
({"\d{1,}", "2"},
{"D", "D"},
{"\d{1,}", "3"})
////////////////////////////////
like image 652
NSediq Avatar asked Jan 21 '26 14:01

NSediq


1 Answers

As mentioned in the comment, you are trying to get the value for each group, thus you need the capturing group () in your regex pattern.

(\d{1,})(D)(\d{1,})

And provide the index to get the value of each group.

string pattern  = @"(\d{1,})(D)(\d{1,})";
string str = "2D3";
var r = new Regex(pattern);
Match match = r.Match(str);

if (match.Success)
{
    Console.WriteLine("1st capturing group: {0}", match.Groups[1]); 
    Console.WriteLine("2nd capturing group: {0}", match.Groups[2]); 
    Console.WriteLine("3rd capturing group: {0}", match.Groups[3]); 
}

I don't think without capturing group(s), you are able to capture each value by portion according to the regex (portion). If you allow the user to input the regex by portion/group as mentioned by @AdrianHHH, then you can manipulate the regex pattern by adding the ( and ) in the front and end respectively.

And since you want to capture each regex pattern and its respective matching value, storing both values in a Dictionary is not a good choice, as Dictionary is not allowed to store the same key.

List<dynamic> Out = new List<dynamic>();
List<string> patternGroups = new List<string> { @"\d{1,}", "D", @"\d{1,}" };

string pattern  = String.Join("", patternGroups.Select(x => $"({x})"));
string str = "2D3";
var r = new Regex(pattern);
Match match = r.Match(str);

if (match.Success)
{           
    for (int i = 0; i < patternGroups.Count; i++)
    {
        Out.Add(new 
                { 
                    Regex = patternGroups[i], 
                    Value = match.Groups[i + 1].Value 
                });
    }
}
like image 198
Yong Shun Avatar answered Jan 24 '26 03:01

Yong Shun