Match class
Example: Finding URLs that are contained in a string
string text =" firsturl:http://www.sohu.com, secondurl:http://www.baidu.com ";
String pattern = @ "\b (\s+)://(\s+) \b";// Pattern matching URL
matchcollection MC = Regex. matches (text, pattern); The matching collection that satisfies pattern
Console.WriteLine (the URL address contained in the text is: ");
foreach (match match in MC)
{
Console.WriteLine (match. Value );
}
Console.ReadLine ();
Results:
Group Class
Example: Find the URL contained in the string and find out the protocol and domain name address for each URL
string text =" firsturl:http://www.sohu.com, secondurl:http://www.baidu.com ";
String pattern = @ "\b (? <protocol>\ s+)://(? <address>\s+) \b "; Matches the pattern of the URL and groups
MatchCollection mc = regex.matches (text, pattern);//Match set for pattern
Console.WriteLine ("URL addresses included in the text are:");
foreach (Match match in MC)
{
GroupCollection gc = match. Groups;
String outputtext = "URL:" + match. Value + "; Protocol:" + gc["Protocol"]. Value + "; Address:" + gc["Address"]. Value;
Console.WriteLine (Outputtext);
}
Console.read ();
Description: "?<protocol>" and "?<address>" define aliases for each group protocol and address
(Note: This is a match within a group that sets different names and extracts these groups)
How do I do the extraction of different groups within a string with the same pattern?
sourcetext:{name:john,data:[1,2,3],name:marry,data:[4,5,6]}
Code:
Regex reg = new Regex (@ "data:\[([\w|.|,]{1,}) \]", regexoptions.ignorecase);
MatchCollection matches = Reg. Matches (series);
foreach (match match in matches)
{
GroupCollection groups = match. Groups;
for (int j = 0; J < groups. Count; J + +)
{
String weightjsoninkgmode = coverttokg (Groups[j]. Value.replace ("data:[", ""). Replace ("]", ""));
String Regmodel = Groups[j]. Value;
Regmodel = Regmodel.replace ("[", "\\["). Replace ("]", "\ \]");
Series = Regex.Replace (series, Regmodel, Weightjsoninkgmode);
}
}
The difference between the regular expression match and the group uses a group extraction case for strings with the same pattern