Jump to content

select all between signs "@:" until next


AndyPSV

Recommended Posts

$string = 'dsadsasddsasda @Andrzej Jeziorski: z\dsadsadsadsasd  @Karol Orzechowski:';
preg_match_all('#@(.*?):#s', $string, $matches);
print_r($matches);

 

Outputs:

 

Array
(
    [0] => Array
        (
            [0] => @Andrzej Jeziorski:
            [1] => @Karol Orzechowski:
        )

    [1] => Array
        (
            [0] => Andrzej Jeziorski
            [1] => Karol Orzechowski
        )

)

A slightly faster RegEx would be

 

@[^:]++

 

The ++ doesn't allow the engine to backtrack. The character class matches anything that's not a :

 

I also removed the capturing group, since we can use string functions to strip the @ off of the result. It saves us from storing almost the exact same string twice in memory.

  Quote

A slightly faster RegEx would be

 

@[^:]++

 

The ++ doesn't allow the engine to backtrack. The character class matches anything that's not a :

 

I also removed the capturing group, since we can use string functions to strip the @ off of the result. It saves us from storing almost the exact same string twice in memory.

 

I don't think the ++ is necessary though...it shouldn't ever backtrack because there's nothing else in the pattern to match for. 

 

Also, to 1up you on using something like trim to get rid of the @...can use \K to have the regex engine ditch it:

 

@\K[^:]+

 

 

Wow, beautifully intricate discussion for such a simple match, I love it!  :)

I thought it was all over in ten minutes after premiso's reply, but no!

 

@.josh, thank you for mentioning \K. I'd read about it without really paying attention as I was on 5.2.1, but recently upgraded to 5.3.8 which supports it. Thank you for pointing it out, I'm going to start using it.

Not yet supported in RegexBuddy by the way, but I found a thread from 8 months ago where Jan (the developer) says it's on the todo list.

 

Wishing you all a fun day.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.