dotws86260 2014-08-07 10:34
浏览 48
已采纳

preg_match substring只有在有效的情况下才有效

I need to extract a substring from an email subject only if valid. The valid substring is like:

ab-2011-0023ad or ac-2011-0023ad.r1, only two dashes are allowed, number of letters after second dash varies, but only alphanumeric with one dot or without dot.

I wrote this one, but if I put after second dash an illegal character, the regexp returns partial substring not empty

/([a-z0-9]{0,3}[-]\d{4}[-][a-z0-9.]+)\S/i

i.e.: "this is an email with ab-2011-0023:ad document", I expect from regexp to return empty array not [0] => ab-2011-0023.

  • 写回答

3条回答 默认 最新

  • doutan3371 2014-08-07 10:52
    关注

    Your reg exp is not correct. 1. Never use one literal in symbolic class like this [-]. You should escape it -, but nod add to symbolic class. 2. [a-z0-9.]+ this piece matches with string "..............". So, it's not correct. 3. In the end you use as delimiter \S (matches everything except the whitespaces).

    My advice is to use smth like this (if your reg exp engine supports Negative Lookbehind)

    /[a-z\d]{0,3}\-\d{4}\-(?:[a-z\d]+|(?<!\.)\.)+\s/i
    

    example

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

报告相同问题?

悬赏问题

  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 被蓝屏搞吐了,有偿求帮解答,Ai回复直接拉黑
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并