double0201 2014-02-15 19:17
浏览 85
已采纳

字符串之后没有空格的正则表达式OR语句将无效

I am trying to get this regex to match (once or twice) any occurrence of these strings: border-box|padding-box|content-box

Here is the regex:

((?:border-box|padding-box|content-box){1,2})

Here is the sample string:

background: url("my image.jpg") left right 2px 50% 75% repeat-x round scroll border-box padding-box;

Expected result:

border-box padding-box

Actual result:

Array
(
    [0] => border-box
    [1] => border-box
)

Oh and btw I am using this site to test my regex: http://www.phpliveregex.com/ Note: I am using preg_match not preg_match_all

  • 写回答

2条回答 默认 最新

  • dongzha0149 2014-02-15 19:21
    关注

    The problem is that your pattern requires the repetitions to occur immediately after each other, with no whitespace between.

    Try adding a \s* after the alternation to allow for optional whitespace between the repetitions, like this:

    (?:(?:border-box|padding-box|content-box)\s*){1,2}
    

    Or even better:

    (?:(?:border|padding|content)-box\s*){1,2}
    

    Note that because of the *, this will also match a string like border-boxborder-box (no whitespace between repetitions). If this is a problem you can try a pattern like this:

    (?:(?:border|padding|content)-box)(?:\s+(?:border|padding|content)-box)?
    

    Note that I've removed the surrounding (…) since this group would always be identical to the entire match, so it's almost certainly not necessary.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器