Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading