【发布时间】:2014-02-24 22:00:48
【问题描述】:
最终解决方案
/(\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
【问题讨论】:
-
你不会通过做任何非贪婪来解决它。正则表达式在 first 位置匹配的事实与贪婪无关。
-
如何改写我的问题以更好地解决这个问题?
-
我不确定,除了“我怎样才能让这个正则表达式匹配我想要的?”想出一个完美的解决方案是一个棘手的问题。
-
(\d{1,5} [^\d]{5,20}(dr|drive)(\.|\s|\,)) -
使第一个字符不是数字是一个聪明的解决方案。这是我的最终解决方案,用那个技巧修改 -
/(\d{1,5}\s[^\d].{5,20}(dr|drive)(\.|\s|\,))/i。
标签: regex pcre regex-greedy non-greedy