dqusbxh44823 2012-04-26 04: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-26 04: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条)

报告相同问题?

悬赏问题

  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里