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"})
////////////////////////////////
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
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With