user690069
user690069

Reputation: 338

match English word with optional dot,slash,numbers existence

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

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

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]+)*$

demo

Upvotes: 0

Explosion Pills
Explosion Pills

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

Related Questions