Shimmy Weitzhandler
Shimmy Weitzhandler

Reputation: 104741

I need a regex that validates for minimum 7 digits in the given string

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

Upvotes: 18

Views: 35122

Answers (3)

rampion
rampion

Reputation: 89063

(?:\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 pattern

If 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 characters

The 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.

Upvotes: 9

Greg Beech
Greg Beech

Reputation: 136627

Why do you want to use regular expressions for this? The first Validate function you posted which simply counts the number of digits is vastly more comprehensible, and probably faster as well. I'd just ditch the unnecessary ToCharArray call, collapse the predicate into the Count function and be done with it:

s.Count(char.IsDigit) >= 7;

Note that if you only want to accept 'normal' numbers (i.e. 0-9) then you'd want to change the validation function, as IsDigit matches many different number representations, e.g.

s.Count(c => c >= '0' && c <= '9') >= 7;

Upvotes: 2

Alan Moore
Alan Moore

Reputation: 75232

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,}$

Upvotes: 43

Related Questions