سؤال

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.

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top