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?
CodePudding user response:
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.
CodePudding user response:
Please try this regex.
^[a-zA-Z][A-Za-z0-9 ()/]*$
You can add whatever special character you want in your regex. Modify it as per your requirement.
CodePudding user response:
Just adding in this in the begining [a-zA-Z]
and at the end [a-zA-Z0-9]
should work.
^[a-zA-Z][a-zA-Z0-9 _-]*[a-zA-Z0-9]$
that means that first char should be a character and the last char should be a character or a number.
Use this: ^[a-zA-Z][a-zA-Z0-9 _-]*[a-zA-Z]$
if it doesnt have to finish with a number.