1

I am new to Regular Expression and tried to write a line of code to match

  1. strings should NOT start with digits. ( OK )
  2. strings should have only alpha, num, dash and underscore in it. ( OK )
  3. strings length should be between 5 and 25 ( FAIL )

rule 1 and 2 works correctly but rule 3 doesn't.

any help to fix it?

This is my code :

$arr = [
    '-foobar',
    'foobar',
    '32-xx',
    'xx23',
    'A2l',
    '2aAA',
    '_a2d',
    '-A22',
    '-34x',
    '2--a',
    'a--a-'

];

foreach( $arr as $a ){
    echo check( $a );
}

function check($string){
    if (preg_match("/^[a-zA-Z]+([a-zA-Z0-9_-]?){5,25}$/", $string)) {
        return "$string ---------------> match was found.<br />";
    } else {
        return "$string ---------------> match was not found.<br />";
    }

}
Pars
  • 4,932
  • 10
  • 50
  • 88

1 Answers1

5

You don't need quantifier + on the first character class. That is just supposed to check the first digit. Then afterwards, you don't need ? quantifier on the 2nd character class. And the range should be {4,24} instead of {3,25}. Also, you can remove the unnecessary capture group from there.

So, modify your regex to:

/^[a-zA-Z][a-zA-Z0-9_-]{4,24}$/
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • I think the whole string should be between 4 and 24 characters long, so `/^([a-zA-Z](?:[a-zA-Z0-9_-])){4,24}$/`. – ComFreek Oct 28 '13 at 18:01
  • @ComFreek No that should not be like that. OP wants length from 5 to 25. – Rohit Jain Oct 28 '13 at 18:02
  • 1
    @aliA `(?:` is to create non-capturing group. I guess you don't want a capturing group here, so just used it. – Rohit Jain Oct 28 '13 at 18:03
  • thank you, I should search for non-capturing at google. I have no idea what it is to decide I want it or not ! :) – Pars Oct 28 '13 at 18:04
  • 1
    @aliA Most probably you won't need it, since you are just matching. Capturing groups are used when you want to use any submatches from your entire matched string. – Rohit Jain Oct 28 '13 at 18:05
  • @aliA In fact, you can remove `(?:` part all together. See the edited regex. – Rohit Jain Oct 28 '13 at 18:08
  • yes, thanks, and I found a good tutorial about non-capturing group in http://stackoverflow.com/questions/3512471/non-capturing-group. :> – Pars Oct 28 '13 at 18:11