Reputation: 479
I have a list of regexes that I iterate through to find a matching pattern for a string.
I want to get the index of the regex that matches entirely with "00000.00", which is 1. However, the regex of 0 also returns true, but should only return true if there is a digit or string of length 5 or 6.
Meaning, 12345 and 123456 should be is valid, but 12345.0 or 123456.0 should not.
List<Regex> regexPatterns = new List<Regex>{
new Regex(@"\b\d{5,6}\b"), // 0
new Regex(@"\b\d{5,6}[.](00)\b") // 1
}
string text = "00000.00";
for( int i = 0; i < regexPatterns.Count; i++ ) {
if( regexPatterns.IsMatch(text) ) return i;
}
This keeps returning 0 for 00000.00 when I want it to return 1.
** The index has a meaning, so reordering them is a no can do.
Upvotes: 0
Views: 79
Reputation: 2095
Check that there is no period in the first one:
List<Regex> regexPatterns = new List<Regex>{
new Regex(@"\d{5,6}[^.]"), // 0
new Regex(@"\d{5,6}[.](00)") // 1
}
string text = "00000.00";
for( int i = 0; i < regexPatterns.Count; i++ ) {
if( regexPatterns.IsMatch(text) ) return i;
}
Upvotes: 0
Reputation: 518
Being that the period will act as a word boundry your best bet is to scan from the most complex pattern to the simplest. You could do your for loop decrementing to accomplish this but another way to consider is to use a dictionary of your patterns with the value component being the return value.
var patterns = new Dictionary<string, int>
{
{ @"\b\d{5,6}\b", 0 },
{ @"\b\d{5,6}[.](00)\b", 1 },
};
string text = "00000.00";
foreach (var pattern in patterns.Keys)
{
if (pattern.IsMatch(text))
return patterns[pattern];
}
Upvotes: 0
Reputation: 32576
Try ^
and $
for the beginning and the end of string:
List<Regex> regexPatterns = new List<Regex>{
new Regex(@"^\d{5,6}$"), // 0
new Regex(@"^\d{5,6}[.](00)$"), // 1
}
See Regular Expression Language - Quick Reference:
^
The match must start at the beginning of the string or line.
$
The match must occur at the end of the string or before\n
at the end of the line or string.
Upvotes: 2