Reputation: 338
I want to match the following words
tree , tree.com , tree123 , 123tree , tree-up ,
I made the following condition..it works properly but I want to join them in one regular expression
bool res1=Regex.IsMatch(term, "^[a-zA-Z-.]+$",RegexOptions.IgnoreCase)
//works well but it matches . and - if they come alone i want a solution ?!
bool res2=Regex.IsMatch(term, "^[a-zA-Z-.]+[0-9]+$",RegexOptions.IgnoreCase) //works well
bool res3=Regex.IsMatch(term,"^[0-9]+[a-zA-Z-.]+$", RegexOptions.IgnoreCase)//works well
I know I can use
if(res1 || res2 || res3 ) {}
but i want to join those expressions in 1 expression
Upvotes: 1
Views: 72
Reputation: 89584
Assuming you do not want leading, trailing or consecutive dots or hyphens, I suggest this pattern:
bool res = Regex.IsMatch(term, "^[a-z0-9]+(?>[-.][a-z0-9]+)*$", RegexOptions.IgnoreCase);
If you want to be sure there's at least one letter, you can change the pattern to:
^(?>[0-9]+(?>[-.][0-9]+)*[-.]?)?[a-z]+(?>[-.]?[a-z0-9]+)*$
Upvotes: 0
Reputation: 191789
You can use a lookahead zero-width assertion to check to make sure that at least one letter (or anything else that is required) is included
^(?=.*[a-zA-Z])[0-9a-zA-Z-.]+$
Upvotes: 1