Mercer
Mercer

Reputation: 9986

A regular expression to exclude a special character

In Spring MVC For validation use @Pattern annotation like this:

@Pattern(regexp = "???", message = "#i18n{obligatoire}")
@NotEmpty   
private String stringTest;

I want just exclude & character. @Pattern(regexp = "^&") it's correct ?

Upvotes: 2

Views: 2525

Answers (1)

Nikolas
Nikolas

Reputation: 44378

^[^&]*?$ is regex you are looking for.

@Pattern(regexp = "^[^&]*$")
@NotEmpty   
private String stringTest;

Explanation:

  • [^&] captures any character that is not &
  • [^&]* captures all characters that are not &
  • ^[^&]*$ captures all characters on the line (^ is the beggining of the line, $ is the end of the line) that are not &

Upvotes: 5

Related Questions