dscizpq790832708 2011-10-27 19:12
浏览 22
已采纳

如何让我的正则表达式提取信息,而不仅仅是检查

I have a regular expression for checking whether a string is zip/postal code or not. But I would really like to also to be able to extract that from a full address (or, if possible, any string).

Here is my current regular expression:

/^((\d{5}-\d{4})|(\d{5})|([a-zA-Z]\d[a-zA-Z]\s\d[a-zA-Z]\d)|([a-zA-Z]\d[a-zA-Z]\d[a-zA-Z]\d))$/

If necessary I'm willing to settle for a function (I'm checking with PHP) but I'd rather the regexp do the work if possible.

  • 写回答

3条回答 默认 最新

  • dpvm7231 2011-10-27 19:20
    关注

    preg_match, which I assume you're already using when you're checking a string against your regular expression, also gives you back the actual text that matched your pattern.

    preg_match($regex, $input, $matches);
    echo $matches[0];
    

    The third argument is filled with the results of trying to match the regex against your input. $matches[0] will contain text that matched the whole pattern, while higher indexes will contain text that matched against capturing subpatterns (the parts of the pattern enclosed in parentheses).

    However, in your case, you've enclosed your pattern with the start-of-input ^ and end-of-input $ characters, which means that any matches must include the entire input string (or an entire line in multiline mode). You'd have to get rid of the ^ and $ before trying to use this pattern to extract a postal code from a larger string.

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

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向