dqusbxh44823 2012-04-25 20:26
浏览 37
已采纳

正则表达式noob需要一个模式来匹配特定的字符串模式

Hi I'm trying to match a search string so that if there is us zipcode is at the beginning of the string, return the matches of the zipcode as well as the rest of the string. This is what i have so far

$str = "90210 Beverly Hills, CA";
$res = preg_match('/^((\d{5})(-\d{4})?)\s+(.+?)$/', $str, $matches);

But when I print_r the matches it returns with an extra key for the space.

Array
(
    [0] => 90210 Beverly Hills, CA
    [1] => 90210
    [2] => 90210
    [3] =>
    [4] => Beverly Hills, CA
)

Is there anyway i can improve the pattern and return matches which is not an empty string? Is there a better pattern for this instance? Also if just a zipcode is given or just a text string, it would return false.

  • 写回答

3条回答 默认 最新

  • doubianxian6557 2012-04-25 20:39
    关注

    The answer is no. A visual inspection of your pattern parentheses indicates that the fourth match would be the -1234 (four extra zip digits -- no idea what they're formally called), and in your example, that is empty. It is a bit unclear from your question what you want to actually capture. I will leave with a construct you may find useful:

    (?: ...)
    

    If you have ?: after a paren, it indicates that a capture should not be made. You can add this before the "dash-four-digit" subpattern and it will not be added to matches.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部