douyuepi6485 2015-04-15 06:19
浏览 20
已采纳

正则表达式:当部分字符串失败时,整个字符串失败

I've read through numerous posts on preg_match and can't find the answer. How to fail the whole preg_match when only one part of the haystack fails? I simply need to fail the whole preg_match, when the haystack ends with dot-anything (e.g., .html).

The groupings in here, before the problem area, are needed for other purposes and can't be changed. The portion I want to fail, when it contains a dot, is: ([^\.])* If that fails, the entire preg_match needs to fail. Note: the dot is only a "failing dot" if it occurs after the hyphen. There are dots before the hyphen that are not failing dots.

Everything on the right-hand side of the OR operator is fine. Nothing needs to be changed there.

preg_match('#^(.*)\/([0-9]+)\-([^\.])*|(.*)id_category=([0-9]+)(.*)$#', $haystack, $return_array)

Since I'm not evaluating the entire string for the dot, I have not been successful with negative lookahead. It only fails the one part, without failing the whole preg_match.

  • 写回答

2条回答 默认 最新

  • douguai7291 2015-04-15 06:25
    关注

    You can add any such condition as a (negative) lookhead at the start of the regex.

    preg_match('#^(?!.*\..+$)((.*)\/([0-9]+)\-([^\.])*|(.*)id_category=([0-9]+)(.*)$)#', $haystack, $return_array)
    

    Here it would fail when there is a '.' with at least one character afterwards. But if you are looking for fileendings, you can e.g. limit the amount of following characters:

    (?!.*\..{1,4}$)
    

    See a simple example here in regex101

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

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大