Reputation: 1475
Regexp in Java I want to make a regexp who do this verify if a word is like [0-9A-Za-z][._-'][0-9A-Za-z] example for valid words
A21a_c32
daA.da2
das'2
dsada
ASDA
12SA89
non valid words
dsa#da2
34$
Thanks
Upvotes: 4
Views: 2005
Reputation: 22446
"(\\p{Alnum})*([.'_-])?(\\p{Alnum})*"
In this solution I assume that the delimiter is optional, the empty string is also legal, and that the string may start/end with the delimiter, or be composed only of the delimiter.
Upvotes: 1
Reputation: 383726
^[0-9A-Za-z]+[._'-]?[0-9A-Za-z]+$
(see matches on rubular.com)
Key points:
^
is the start of the string anchor$
is the end of string anchor+
is "one-or-more repetition of"?
is "zero-or-one repetition of" (i.e. "optional")-
in a character class definition is special (range definition)...
.
unescaped outside of a character class definition is special...
Upvotes: 2
Reputation: 8786
If [._'-]
are optional, put the ?
with the next characters, like this:
[0-9A-Za-z]+([._'-][0-9A-Za-z]+)?
Upvotes: 1