Reputation: 67898
I need a RegEx that fulfills this statement:
There is at least one character and one digit, regardless of order, and there is no suffix (i.e. domain name) at the end.
So I have this test list:
ra182
jas182
ra1z4
And I have this RegEx:
[a-z]+[0-9]+$
It's matching the first two fully, but it's only matching the z4
in the last one. Though it makes sense to me why it's only matching that piece of the last entry, I need a little help getting this the rest of the way.
Upvotes: 1
Views: 594
Reputation: 43673
I suggest to use
Match match = Regex.Match(str, @"^(?=.*[a-zA-Z])(?=.*\d)(?!.*\.).*");
or
Match match = Regex.Match(str, @"^(?=.*[a-zA-Z])(?=.*\d)(?!.*[.]).*");
or
Match match = Regex.Match(str, @"^(?=.*[a-zA-Z])(?=.*\d)[^.]*$");
or
Match match = Regex.Match(str, @"^(?=.*[a-zA-Z])[^.]*\d[^.]*$");
if (match.Success) ...
Upvotes: 0
Reputation: 106385
You can check the first two conditions with lookaheads:
/^(?=.*[a-z])(?=.*[0-9])/i
... and if the third one is just about the absence of .
, it's simple to check too:
/^(?=.*[a-z])(?=.*[0-9])[^.]+$/i
But I'd probably prefer to use three separate tests instead: with first check for symbols (are you sure it's enough to check just for a range - [a-z] - and not for a Unicode Letter
property?), the second for digits, and the final one for this pesky dot, like this:
if (Regex.IsMatch(string, "[a-zA-Z]")
&& Regex.IsMatch(string, "[0-9]")
&& ! Regex.IsMatch(string, @"\.") )
{
// string IS valid, proceed
}
The regex in the question will try to match one or more symbols, followed by one or more digits; it obviously will fail for the strings like 9a
.
Upvotes: 4
Reputation: 39013
You need to match alphanumeric strings that have at least one letter and one number? Try something like this:
\w*[a-z]\w*[0-9]\w*
This will make sure you have at least one letter and one number, with the number after the letter. If you want to take into account numbers before letters, just use the corresponding expressiong (numbers before letters) and |
the two.
Upvotes: -1