Regular expression for exactly N elements, no less, no more
I'm trying to figure out that a regex to find matches with exact N occurrences of at least, at most, a group of characters. This looks like a pretty straightforward task, but I haven't been able to find the correct regex for it.
Specifically, I want a regex to indicate whether a given string contains exactly 3 digits - no less, no more.
I thought I could accomplish this simply by treating the 3 digits as a group and adding the {1} quantifier after it, but that doesn't work.
Alternatively, I expected [0-9] [0-9] [0-9] to work, but again it doesn't. Both regular expressions return the same results as the input set as 1, 12, 123, 1234, 12345.
Below is some sample code that accomplishes what I have tried as described above.
class Program
{
static void Main(string[] args)
{
List<Regex> regexes = new List<Regex> { new Regex("\\d{3}"), new Regex("[0-9][0-9][0-9]"), new Regex("(\\d{3}){1}") };
List<int> numbers = new List<int> { 1, 12, 123, 1234, 12345 };
foreach(Regex regex in regexes)
{
Console.WriteLine("Testing regex {0}", regex.ToString());
foreach (int number in numbers)
{
Console.WriteLine(string.Format("{0} {1}", number, regex.IsMatch(number.ToString()) ? "is a match" : "not a match"));
}
Console.WriteLine();
}
}
}
Output to the program above:
Clearly only 123 matches all input values. What would be a regex that only considers "123" to be a match?
source to share
All your regexes are calculated to be 3 digits anywhere in the input. You are looking for:
new Regex("^\\d{3}$")
^
matches the beginning of the input, and $
matches the end of the input. So this regex says, "There should be three digits from the beginning and then wait for the end."
source to share
You must prefix ^
to indicate the beginning of the line and $
to indicate the end of it. See http://regexr.com/3be8e for a working example.
source to share