0

I need a regex that allows 0-9, a-z, A-Z, hyphen, question mark and "/" slash characters alone. Also the length should be between 5 to 15 only.

I tried as follows, but it does not work:

var reg3 = /^([a-zA-Z0-9?-]){4,15}+$/;
alert(reg3.test("abcd-"));
3
  • you need to change the 4 to a 5 at least Commented May 8, 2014 at 14:57
  • If you want between 5 and 15, why did you write {4,15}? Also, what is {4,15}+ supposed to mean? The + means {0,}, it's not needed. Commented May 8, 2014 at 14:57
  • 1
    Try some online regex editor, it will help you learn quicker because you can play with the regex. refiddle is an example. Commented May 8, 2014 at 15:00

3 Answers 3

4

length should be between 5 to 15 only

Is that why you have this?

{4,15}+

Just use {5,15}; it’s already a quantifier, and a + after it won’t work. Apart from that, the group isn’t necessary, but things should work.

/^[a-zA-Z0-9?/-]{5,15}$/

(I also added a slash character.)

Sign up to request clarification or add additional context in comments.

Comments

0

This is what you need:

if (/^([a-z\/?-]{4,15})$/i.test(subject)) {
    // Successful match
} else {
    // Match attempt failed
}

REGEX EXPLANATION

^([a-z\/?-]{4,15})$

Options: Case insensitive

Assert position at the beginning of the string «^»
Match the regex below and capture its match into backreference number 1 «([a-z\/?-]{4,15})»
   Match a single character present in the list below «[a-z\/?-]{4,15}»
      Between 4 and 15 times, as many times as possible, giving back as needed (greedy) «{4,15}»
      A character in the range between “a” and “z” (case insensitive) «a-z»
      The literal character “/” «\/»
      The literal character “?” «?»
      The literal character “-” «-»
Assert position at the very end of the string «$»

Comments

0

Couple issues,

  1. you need {5,15} instead of {4,15}+
  2. need to include /

Your code can be rewritten as

var reg3 = new RegExp('^[a-z0-9?/-]{5,15}$', 'i'); // i flag to eliminate need of A-Z
alert(reg3.test("a1?-A7="));

Update

Let's not confuse can be with MUST be and concentrate on the actual thing I was trying to convey.

{4,15}+ part in /^([a-zA-Z0-9?-]){4,15}+$/ should be written as {5,15}, and / must be included; which will make your regexp

/^([a-zA-Z0-9?/-]){5,15}$/

which CAN be written as

/^[a-z0-9?/-]{5,15}$/i   // i flag to eliminate need of A-Z

Also I hope everybody is OK with use of /i

3 Comments

You know you can do var reg3 = /^([a-z0-9?\-]){5,15}$/i;, right? You don't need to use new RegExp.
Yes that's true (and I know).
Can be rewritten? Sure, but it’s not better. new RegExp is inappropriate on static strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.