Search code examples
regexpcreregex-greedynon-greedy

How do I make a part of my Regex non-greedy?


FINAL SOLUTION

/(\d{1,5}\s[^\d].{5,20}(dr|drive)(\.|\s|\,))/i

ORIGINAL QUESTION

Regex

/([0-9]{1,5}.{5,20}(dr|drive)(\.|\s|\,))/i

Pattern

PO Box 66 23 Britton Drive Bloomfield CT 06002

This regex is returning '66 23 Britton Drive'. I want to return '23 Britton Drive'. I have tried the following variations of the Regex:

/(([0-9]{1,5}.{5,20})?(dr|drive)(\.|\s|\,))/i - adding a new capturing group and making it uncreedy
/([0-9]{1,5}.{5,20}?(dr|drive)(\.|\s|\,))/i - making the length of in between characters ungreedy
/([0-9]{1,5}.{5,20}(dr|drive)(\.|\s|\,))/Ui - adding ungreedy modifier

More Patterns That Don't Work

PO Box 156 430 S Wheeling Dr. Wheeling, IL 60090

Patterns That Do Work

1195 Columbia Dr PO Box 1256 Longview, WA 98632
3400 SW Washington drive PO Box 1349 Peoria, IL 61654

Solution

  • ^[^\d]+\d{2} (\d{2} [^ ]+ [^ ]+)
    

    Regular expression visualization

    Debuggex Demo

    Obviously, i'd need more patterns to make this work for all situations

    Small fix for your current RegEx

    (\d{1,5} [^\d]{5,20}(dr|drive)(\.|\s|\,))