Here is an ugly brute force extension for parsing without using another Regex to detect a subexpression (or subpattern):
public static string GetSubExpression(this Regex pRegex, string pCaptureName) { string sRegex = pRegex.ToString(); string sGroupText = @"(?<" + pCaptureName + ">"; int iStartSearchAt = sRegex.IndexOf(sGroupText) + sGroupText.Length; string sRemainder = sRegex.Substring(iStartSearchAt); string sThis; string sPrev = ""; int iOpenParenCount = 0; int iEnd = 0; for (int i = 0; i < sRemainder.Length; i++) { sThis = sRemainder.Substring(i, 1); if (sThis == ")" && sPrev != @"\" && iOpenParenCount == 0) { iEnd = i; break; } else if (sThis == ")" && sPrev != @"\") { iOpenParenCount--; } else if (sThis == "(" && sPrev != @"\") { iOpenParenCount++; } sPrev = sThis; } return sRemainder.Substring(0, iEnd); }
Usage is as follows:
Regex reFromUser = new Regex(txtFromUser.Text); string[] asGroupNames = reFromUser.GetGroupNames(); int iItsInt; foreach (string sGroupName in asGroupNames) { if (!Int32.TryParse(sGroupName, out iItsInt))
Now, if you want to generate test data or sample data, you can use the NuGet package called "Fare" as follows after receiving the subexpression:
//Generate test data for it Fare.Xeger X = new Fare.Xeger(sSubExpression); string sSample = X.Generate();
source share