Reputation: 47
I have a regular expression (@"[0-9\. \-\*\(\)]*"
) to allow only certain characters in my string. I want to know how I can also check that the string contains at least 5 of a subset of those characters namely [0-9]
.
I could use @"[0-9]{5,}"
but this wouldn't allow for the other characters I want allowed in the input.
I could use @"[0-9\. \-\*\(\)]{5,}"
but this would allow inputs that don't contain 5 digits.
I could use @"[0-9]{5,}[0-9\. \-\*\(\)]*"
but this would require the 5 digits to be at the beginning of the input.
How can I check my input has at least 5 digits while still allowing other characters?
--
For example, I want to match:
12345
or 123 4-5
but not
1 3-5
or *- 4--*
.
Upvotes: 1
Views: 452
Reputation: 26907
Most characters are not special in a character group, so you don't need to escape them.
@"[0-9. *()-]{5,}(?<=([. *()-]*[0-9][. *()-]*){5,})";
This pattern says find a string of at least five valid characters, then verify the end of that string is preceded by a string of valid characters containing at least 5 digits.
I assume there was a reason your original expression didn't restrict the match to the whole string (locating the phone number?) but if you need the whole string to match:
@"^(?=(.*[0-9].*){5})[0-9. *()-]{5,}$"
This is somewhat simpler - check the string has at least 5 digits and consists only of valid characters. If you need to include the empty string, it would need a change.
If you are trying to validate phone numbers, both expressions are too simple, as they will accept strings like ((())12--33--44
.
Upvotes: 2