tinti
tinti

Reputation: 1475

Regexp match in Java

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

Answers (3)

Eyal Schneider
Eyal Schneider

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

polygenelubricants
polygenelubricants

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)...
    • unless it's escaped, or first, or last
  • . unescaped outside of a character class definition is special...
    • but in a character class definition it's just a period

References

Upvotes: 2

True Soft
True Soft

Reputation: 8786

If [._'-] are optional, put the ? with the next characters, like this:

[0-9A-Za-z]+([._'-][0-9A-Za-z]+)?

Upvotes: 1

Related Questions