0

Is it possible to use quantifiers with groups?

For example. I want to match something like:

  • 11%
  • 09%
  • aa%
  • zy%
  • g1%
  • 8b% ...

The pattern is: 2 letters or numbers (mixed, or not) and a % ending the string ...

<?php
echo preg_match('~^([a-z]+[0-9]+){2}%$~', 'a1%'); // 0, I expect 1.

I know, this example doesn't make too much sense. A simple [list]{m,n} would solve this one. It's as simples as possible just to get an answer.

ekad
  • 14,436
  • 26
  • 44
  • 46
Thom Thom Thom
  • 1,279
  • 1
  • 11
  • 21
  • I don't think that regular expression matches what you want it to match. That regular expression matches one or more letters, followed by one or more numbers, *twice*, then a % and the end of the string. So `a1a1%` would match. I think what you meant to write is `/^([a-z]|[0-9]){2}%$/`. Which will match the string you gave, as well as being an example for your desire to use quantifiers with groups (which is totally legit, as per @jerry 's response). – FrankieTheKneeMan May 23 '13 at 14:57

2 Answers2

1

You sure can apply quantifiers to groups. For example, I have the string:

HouseCatMouseDog

And I have the regex:

(Mouse|Cat|Dog){n}

Where n is any number. You can play around changing the value of n here.

As for your example (yes, [list]{m,n} would be simpler), it will work only if there is an alphabet or more, followed by a number, or more. As such, only g1 will match.

Jerry
  • 70,495
  • 13
  • 100
  • 144
0

You don't need use 2 characters classes, only one would do your job.

echo preg_match('~^([a-z0-9]{2})%$~', 'a1%'); 

RegExp meaning

^ => It will match at beggining of the string/line
(
    [a-z0-9] => Will match every single character that match a-z(abcdefghijklmnopqrstuvwxyz) class and 0-9(0123456789) class.
    {2} => rule above must be true 2 times
) => Capture block
% => that character must be matched after a-z and 0-9 classes
$ => end of string/line
  • Following this example it MUST start with a letter. Thanks. – Thom Thom Thom May 23 '13 at 14:13
  • 2
    @ThomThomThom It can start with a number. Character classes don't look at the order of characters within them. In the regex above, you can have a situation where there are no letters at all, and it will still match. – Jerry May 23 '13 at 14:14