Home > Software design >  Find all occurrences of regex pattern in string
Find all occurrences of regex pattern in string

Time:12-16

I have the following code:

var varFormula = "IIF(ABCCF012HIZ3000=0,0,ABCCF012HCZ3000/ABCCF012HIZ3000)"
MatchCollection match = Regex.Matches(varFormula, @"^AB([CC|DD|EE] [F|G])[0-9]{3}(HI|IC|HC)Z[A-Z0-9]{4}$", RegexOptions.IgnoreCase);

From above, I want to extract the following from varFormula but I'm not able to get any matches/groups:

ABCCF012HCZ3000
ABCCF012HIZ3000

CodePudding user response:

Your regex uses ^ and $ which designate the start and end of a line. So it will never match the varFormula. Try the following:

var varFormula = @"IIF(ABCCF012HIZ3000=0,0,ABCCF012HCZ3000/ABCCF012HIZ3000)";
MatchCollection match = Regex.Matches(varFormula, @"AB(?:[CC|DD|EE] [F|G])[0-9]{3}(?:HI|IC|HC)Z[A-Z0-9]{4}", RegexOptions.IgnoreCase)

Should give you three matches:

Match 1 ABCCF012HIZ3000
Match 2 ABCCF012HCZ3000
Match 3 ABCCF012HIZ3000
  • Related