6

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.

aelor
  • 10,892
  • 3
  • 32
  • 48
Joe
  • 4,460
  • 19
  • 60
  • 106
  • possible duplicate of [Regex - Should hyphens be escaped?](http://stackoverflow.com/questions/9589074/regex-should-hyphens-be-escaped) – Robin Apr 03 '14 at 09:26

2 Answers2

6

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.

djm.im
  • 3,295
  • 4
  • 30
  • 45
sshashank124
  • 31,495
  • 9
  • 67
  • 76
  • @sshashank124: Be careful, `\w` also matches `_` as it's a shorthand for `[a-zA-Z0-9_]`. Also, escaping the `-` is unnecessary when at the very beginning or end of the character class. – Robin Apr 03 '14 at 09:28
6

- 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)

Robin
  • 9,415
  • 3
  • 34
  • 45
  • @Edan: Please see mine, I think you are confused about the character class role itself. – Robin Apr 03 '14 at 09:21