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
        )

)

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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[^:]+

 

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.