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 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应