I wanna validate a phone number. My condition is that I want mimimum 7 numbers in the given string, ignoring separators, X, parantheses.
Actually I want to achieve this function in regex:
Func<string, bool> Validate = s => s.ToCharArray().Where(char.IsDigit).Count() >= 7;
Func<string, bool> RegexValidate = s => System.Text.RegularExpressions.Regex.IsMatch(s, @"regex pattern should come here.")
string x = "asda 1234567 sdfasdf";
string y = "asda sdfa 123456 sdfasdf";
bool xx = Validate(x); //true
bool yy = Validate(y); //false
The purpose of my need is I want to include this regex in an asp:RegularExpressionValidator
By combining the interval quantifier with the surrounding start- and end-of-string anchors, the regex will fail to match if the subject text's length falls outside the desired range.
With regex you have a couple of options to match a digit. You can use a number from 0 to 9 to match a single choice. Or you can match a range of digits with a character group e.g. [4-9]. If the character group allows any digit (i.e. [0-9]), it can be replaced with a shorthand (\d).
To validate a RegExp just run it against null (no need to know the data you want to test against upfront). If it returns explicit false ( === false ), it's broken. Otherwise it's valid though it need not match anything. So there's no need to write your own RegExp validator.
+: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.
Seven or more digits, mixed with any number of any other kind of character? That doesn't seem like a very useful requirement, but here you go:
^\D*(?:\d\D*){7,}$
(?:\d.*){7,}
(?:...)
- group the contained pattern into an atomic unit\d
- match a digit.*
match 0 or more of any character{7,}
match 7 or more of the preceeding patternIf the only separators you want to ignore are spaces, dashes, parentheses, and the character 'X', then use this instead:
(?:\d[- ()X]*){7,}
[...]
creates a character class, matching any one of the contained charactersThe difference being, for example, that the first regex will match "a1b2c3d4e5f6g7h"
, and the second one won't.
As Gregor points out in the comments, the choice of regex depends on what function you're using it with. Some functions expect a regex to match the entire string, in which case you should add an extra .*
in front to match any padding before the 7 digits. Some only expect a regex to match part of a string (which is what I expected in my examples).
According to the documentation for IsMatch()
it only "indicates whether the regular expression finds a match in the input string," not requires it to match the entire string, so you shouldn't need to modify my examples for them to work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With