Nick Div Nick Div - 5 months ago 8
Java Question

Regex to use in Pattern annotation for dot appearing maximum once.

I want a Regex that I want to use in Java Pattern annotation to match with a String that contains maximum one dot.

I found a Regex that works outside Java here:
http://stackoverflow.com/a/37890308/1787314

I am not sure why but the Regex doesn't seem to work when passed in the Pattern annotation.

@Pattern(regex = "^[^.]*(?:\\.[^.]*)?$")
private String name;


This is the behavior that I am expecting.

Nick.Div -- Matches
NickDiv -- Matches
Nick.Div. -- Doesn't Match
Nic.k.Div -- Doesn't Match


I tried manipulating the Regex a bit inside the annotation but all failed.

I would really appreciate some help on this.

Answer

Use this pattern:

"^[^.]*\\.[^.]*$"

Online Demo

  • " delimiter
  • ^ first of string
  • [^.]* a character class which matches zero or more of everything except .
  • \\. matches a dot . literally
  • $ end of string
Comments