Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to allow hyphens using regex

Tags:

java

regex

struts

I want the user to enter hyphens with the following code

<var>
    <var-name>mask</var-name>
    <var-value>^[a-zA-Z0-9]*$</var-value>
</var>

I am using struts validation. so please help me to address this.

EDIT

the user can enter the hyphens anywhere in the string,so there is no restriction on whether the - should be at the beginning, middle or end.

like image 882
Joe Avatar asked Dec 25 '22 11:12

Joe


2 Answers

You should escape it as follows:

<var>
    <var-name>mask</var-name>
    <var-value>^[a-zA-Z0-9\-]*$</var-value>
</var>

This is because - is a special construct in regex and therefore if you want to treat it literally, escape it.

like image 129
sshashank124 Avatar answered Jan 11 '23 07:01

sshashank124


- is a special character inside a character class, you can 'escape' it by putting it at the beginning or the end:

[-a-zA-Z0-9]

This character class will match one character, either:

  • a hyphen -
  • or a letter (upper or lowercase)
  • or a digit

When you use it that way: ^[-a-zA-Z0-9]*$, you ensure that your string is composed only by these characters (no restriction on the position of the hyphen or the other possible characters)

like image 44
Robin Avatar answered Jan 11 '23 08:01

Robin