Java pattern: regexp – Allow few special character in between character

I am trying to allow some character through regular expression. I want to allow word with special character like ( – _ & spaces) in between the character. Also i am allowing number in a word along with letter.

Valid:

a_B
a_b
a b
a B
a_btest_psom
a-B
a43 b
a43_c

Invalid:

a_
_a
a-
a_b_
a_B_
a_b-
a_btest_psom_ (at end only special character)
43 b (starting with number)
43_c (starting with number)
434343 (only numbers)

Code:

import javax.validation.constraints.Pattern;

public static final String PATTERN="^[a-zA-Z0-9 _-]*$"; 
@Pattern(regexp = PATTERN)
private String companyName;

Using above code, I am not able to achieve as per my expectation. Can you help me on this?

>Solution :

You can use

^[a-zA-Z][a-zA-Z0-9]*(?:[ _-][a-zA-Z0-9]+)*$

See the regex demo

Details:

  • ^ – start of string
  • [a-zA-Z][a-zA-Z0-9]* – a letter and then zero or more letters or digits
  • (?:[ _-][a-zA-Z0-9]+)* – zero or more sequences of a space/_/- and then one or more letters or digits
  • $ – end of string.

Leave a Reply