简体   繁体   中英

What's wrong with this regex expression?

i want to preg_match the following code:

{{{/foo:bar/a/0/b}}}

This is my regex (which doesn't work, and i don't understand why):

|{{{\/([[:alpha:]][[:alnum:]\_]*\:[[:alpha:]][[:alnum:]\_]*)(?:\/([[:alnum:]\_]*))+}}}|Uism

Expected result:

Array (
[0] => Array
    (
        [0] => {{{/foo:bar/a/0/b}}}
    )

[1] => Array
    (
        [0] => foo:bar
    )

[2] => Array
    (
        [0] => a
    )

[3] => Array
    (
        [0] => 0
    )

[4] => Array
    (
        [0] => b
    )
)

The result i get:

Array (
[0] => Array
    (
        [0] => {{{/foo:bar/a/0/b}}}
    )

[1] => Array
    (
        [0] => foo:bar
    )

[2] => Array
    (
        [0] => b
    )
)

I only get the last element back. So what's wrong with it?

You're repeating the second capturing group:

(?:
 \/
 (
  [[:alnum:]\_]*
 )
)+

On each repetition of the outer non-capturing group, the contents of the inner capturing group are overwritten, which is the reason why only the last match is preserved. This is standard behavior across all regex engines.

(?=(^.*$)|(?:\/(.*?)(?:\/|})))

Try this.See demo.

http://regex101.com/r/lS5tT3/3

Each subsequent match of the same capture group will overwrite the previous one; that's why you end up with just b .

What I would suggest in this case is to match the whole block first and then use a simpler explode() to dig out the inner data; use this expression:

|{{{\/([[:alpha:]][[:alnum:]\_]*\:[[:alpha:]][[:alnum:]\_]*(?:\/[[:alnum:]\_]*)+)}}}|U

Then, with the resulting $matches array (third argument to preg_match() ):

$data = explode('/', $matches[1]);

Your pattern is complete overkill for something that should be quite simple:

$rex = "@[{]{3}/(\w+:\w+)/(\w)/(\d)/(\w)[}]{3}@";
$str = "{{{/foo:bar/a/0/b}}}";

preg_match($rex, $str, $res);

Result:

Array
(
    [0] => {{{/foo:bar/a/0/b}}}
    [1] => foo:bar
    [2] => a
    [3] => 0
    [4] => b
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM