Reputation: 14399
EDITED
How to write regex that will check if string's length is 8 or more and it contains only digits then it should contain at least one alphabetical character. For example:
Upvotes: 1
Views: 226
Reputation: 24676
If you are using c#, you can simplify your life and use two separate regex:
bool res = false;
string str = // your string
if (str < 8)
{
res = Regex.IsMatch(str, @"^[0-9]+$");
}
else
{
res = Regex.IsMatch(str, @"^(?=[a-zA-Z0-9]*[a-zA-Z])[a-zA-Z0-9]*$");
}
Upvotes: 0
Reputation: 10347
try this Regex
:
^(\d{0,7}|(\d*[a-zA-Z]\d*)+)$
and your code can like this:
var str = new List<string> {"1234567", "1234a5678", "12345678"};
foreach (string s in str)
{
var isValid = Regex.IsMatch(s, @"^(\d{0,7}|(\d*[a-zA-Z]\d*)+)$");
}
Upvotes: 0
Reputation: 354546
Because the question changed my initial regex solution wouldn't work anymore. In fact, it's hard to do with a single regex now. So another option:
bool Validate(string s) {
int numDigits = s.Count(c => char.IsNumber(c));
if (numDigits <= 7) {
return numDigits == s.Length;
} else {
int numLetters = s.Count(c => char.IsLetter(c));
return numLetters > 0 && numDigits + numLetters == s.Length;
}
}
Upvotes: 1
Reputation: 4966
int Digits(string input) {
{
int count = 0;
foreach (char c in str)
{
if (c > '0' && c < '9')
count++;
}
return count;
}
bool IsValid(string input)
{
if (Digits(input) <= 8) {
// is numeric
return Regex.IsMatch(input, @"^[0-9]+$");
}
else {
// has alpha && is alpha-numeric
return Regex.IsMatch(input, @"[a-zA-Z]+") && Regex.IsMatch(input, @"^[0-9a-zA-Z]+$");
}
}
Upvotes: 0
Reputation: 515
If you want to create & test your regex, don't hesitate to use this regex.powertoy.org
Upvotes: 0