如何让我的正则表达式的一部分非贪婪?

时间:2014-02-01 01:43:02

标签: regex pcre regex-greedy non-greedy

最终解决方案

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

原始问题

正则表达式

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

模式

PO Box 66 23 Britton Drive Bloomfield CT 06002

这个正则表达式正在回归'66 23 Britton Drive'。我想回归'23 Britton Drive'。我尝试了以下正则表达式的变体:

/(([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

更多不起作用的模式

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

有效的模式

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

1 个答案:

答案 0 :(得分:1)

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

Regular expression visualization

Debuggex Demo

显然,我需要更多模式才能使其适用于所有情况

针对当前RegEx的小修复

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