Udaychandra shivade
Udaychandra shivade

Reputation: 43

Regex for at least one alphabet and shouldn't allow dot(.)

I have written the regex below but I'm facing an issue:

^[^\.]*[a-zA-Z]+$

As per the above regex, df45543 is invalid, but I want to allow such a string. Only one alphabet character is mandatory and a dot is not allowed. All other characters are allowed.

Upvotes: 4

Views: 1599

Answers (4)

Nader Hisham
Nader Hisham

Reputation: 5414

you can add the first part of your regex which is ^[^.]* to the end to be like this

^[^.]*[A-Za-z]+[^.]*$

try this Demo

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627507

Just add the digits as allowed characters:

^[^\.]*[a-zA-Z0-9]+$

See demo

In case you need to disallow dots, and allow at least 1 English letter, then use lookaheads:

^(?!.*\.)(?=.*[a-zA-Z]).+$

(?!.*\.) disallows a dot in the string, and (?=.*[a-zA-Z]) requires at least one English letter.

See another demo

Another scenario is when the dot is not allowed only at the beginning. Then, use

^(?!\.)(?=.*[a-zA-Z]).+$

Upvotes: 6

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89639

You can use this:

^[^.a-z]*[a-z][^.]*$

(Use a case insensitive mode, or add A-Z in the character classes)

Upvotes: 0

anubhava
anubhava

Reputation: 786146

You need to use lookahead to enforce one alphabet:

^(?=.*?[a-zA-Z])[^.]+$

(?=.*?[a-zA-Z]) is a positive lookahead that makes sure there is at least one alphabet in the input.

Upvotes: 2

Related Questions