我正在尝试从以下内容中提取郊区名称
:
12 street name, suburb name, CTG 1234
在 PHP 中使用正则表达式。
- 街道和郊区名称的长度可以是任意数量。
- CTG 是 state 的缩写,总是已知且始终相同。
- 后面是 4 位数的邮政编码。
我想出了以下正则表达式,但无法完全理解我想要的内容。
/[\.|,]+\s*(.*?)[\.|,]+*\s*CTG\d{4,4}$/i
地点:
CTG\d{4,4}$
是从左边查找邮政编码和州。[\.|,]*\s*
匹配街道和郊区名称后至少一个点或逗号,后跟零个或多个空格。(.*?)
是捕获我的目标。郊区名称。*?
所以它将是非贪婪的。
上面在 preg_match() 中使用,任何给定主题都会返回匹配数组,其中:
arrey[0]
= 整个比赛arrey[1]=12
= 街道名称、郊区名称
但是如果在 http://www.regexplanet.com 中尝试过看起来效果很好。
最佳答案
您可以通过以下方式获取郊区名称:
$str = '12 street name, suburb name, CTG 1234';
$pattern = '/[^.,]++(?=[.,]\s*CTG \d{4}$)/';
preg_match($pattern, $str, $result);
echo $result[0];
为了仅匹配郊区名称,我使用了前瞻断言 (?=...)
,该断言仅执行检查而不记录匹配。
图案详细信息:
/
[^.,]++ # all that is not a . or a , one or more times (possessive)
(?= # open lookahead assertion (means "followed by")
[.,]\s* # a . or a , with optional white characters
CTG \d{4}$ # CTG, a space, four digits, end of string
) # close the lookahead
/
关于php - 尝试使用正则表达式从 php 中的 "suburb name"中提取 "12 street name, suburb name, CTG 1234",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19334417/