Reputation: 33
Im having difficulty constructing a regex validation for laravel that accepts only characters or only digits. It goes something like this:
my regex right now is something like this: [A-Za-z]|[0-9].
Any help is appreciated
Upvotes: 3
Views: 657
Reputation: 5859
Take a look at this Regex:
^[a-zA-Z]+$|^[0-9]+$
You were close, but you must add the start of line ^
and end of line $
tags, as well as the +
to match at least 1 to unlimited times.
Explanation:
^ # start of line
[a-zA-Z]+ # match a-zA-Z recursively
$ # end of line
| # OR
^ # start of line
[0-9]+ # match [0-9] recursively
$ # end of line
Bonus:
If you have a block text and you want to extract matches that are either only letters or only digits, instead of start and end characters you can use word boundaries:
\b[a-zA-Z]+\b|\b[0-9]+\b
Upvotes: 5