Search code examples
javaregexstruts

how to allow hyphens using regex


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.


Solution

  • 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.