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

    Join Date
    Aug 2013
    Posts
    3
    Rep Power
    0

    Question Optional capture group


    I want to match test.nl.example.org and then my first match group is test.nl. Therefor is use this regex:
    Code:
    ([\w\.-]+)\.example.org
    But now I want if there is any options given (with opt-) I want that options in the second capture group:
    Code:
    ([\w\.-]+)(?:\.opt-((ob|co|re|-co|-re|-ob|\b)+))\.example.org
    So the $2 of test.nl.opt-ob.example.org is: ob

    Unfortunately the regex doesn't match test.nl.example.org can I make from the second group a optional group?

    I've tried this:
    Code:
    ([\w\.-]+)(?:\.opt-((ob|co|re|-co|-re|-ob|\b)+))?\.example.org
    but then the content of $2 is empty.

    I hope that someone can help me with this.

    RegExr link:
    http://gskinner.com/RegExr/?365nf
  2. #2
  3. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,068
    Rep Power
    9398
    + is greedy by default, meaning it'll match as much as it possibly can before the regular expression engine will backtrack and try to match the rest. Your opt-* thing is optional so it'll just skip that entirely.

    Use the ungreedy version +?, which will match as little as possible, with your latest attempt.

    Comments on this post

    • Alwaysup agrees : Thanks!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    3
    Rep Power
    0

    Thumbs up


    Originally Posted by requinix
    + is greedy by default, meaning it'll match as much as it possibly can before the regular expression engine will backtrack and try to match the rest. Your opt-* thing is optional so it'll just skip that entirely.

    Use the ungreedy version +?, which will match as little as possible, with your latest attempt.
    Thanks it's working, this is my final regex:
    Code:
    ([\w\.-]+?)(?:\.opt-((ob|co|re|-co|-re|-ob|\b)+))?\.example.org

IMN logo majestic logo threadwatch logo seochat tools logo