#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2007
    Location
    Abertawe, Cymru
    Posts
    29
    Rep Power
    0

    Going backwards with regex


    Hey,

    I don't know regex but would like to learn.

    I want to pattern match the following in php...

    A name which can be in the format....

    abc/123456789@home
    abc/xyz/123456789@192.168.0.1
    123/abc/xyz/123456789@192.168.0.1

    I want to get the long number in the middle which will always be between the last / and the @

    Because I don't know how many '/'s there will be, is it possible to look backwards in regex to find the @ and then the / and then select the part in between?

    Start with something like:

    ?<=@[0-9]

    That's a wild guess! I hope you guys can help me out!
  2. #2
  3. No Profile Picture
    User 165270
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2005
    Posts
    497
    Rep Power
    937
    Although learning regex would be better by starting with some basic tutorials, here's a demo:

    PHP Code:
    $text '123/abc/xyz/123456789@192.168.0.1';

    echo 
    preg_replace('/^.*?(\d+)@.*$/'"$1"$text);

    // or
    if(preg_match('/\d+(?=@)/'$text$match)) {
        echo 
    "\n" $match[0];

  4. #3
  5. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,690
    Rep Power
    6351
    Right, you don't need lookarounds for this, just anchor to the end of the string.

    Also, if your "big number" contains things that are NOT numbers, the above regex won't work. Calling "abc123" a "number" is a common mistake around here.

    -Dan
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.

IMN logo majestic logo threadwatch logo seochat tools logo