代码之家  ›  专栏  ›  技术社区  ›  Spoike Otávio Décio

正则表达式匹配%

  •  3
  • Spoike Otávio Décio  · 技术社区  · 16 年前

    我试图匹配包含在%中的子字符串,但是 preg_match_all 似乎在同一行中同时包含多个。

    代码如下所示:

    preg_match_all("/%.*%/", "%hey%_thereyou're_a%rockstar%\nyo%there%", $matches);
    print_r($matches);
    

    Array
    (
        [0] => Array
            (
                [0] => %hey%_thereyou're_a%rockstar%
                [1] => %there%
            )
    
    )
    

    但是,我希望它生成以下数组:

    [0] => %hey%
    [1] => %rockstar%
    [2] => %there%
    

    我错过了什么?

    6 回复  |  直到 16 年前
        1
  •  12
  •   Adam Batkin    16 年前

    更换“ . “在正则表达式中使用” [^%] ":

    preg_match_all("/%[^%]*%/", "%hey%_thereyou're_a%rockstar%\nyo%there%", $matches);
    

    正在发生的是“ . “贪婪”匹配尽可能多,包括行中最后%的所有内容。将其替换为否定字符类 [^%] 除了

    另一个选择是放置一个“ ? 在圆点之后,它告诉它“不要贪婪”:

    preg_match_all("/%.*?%/", "%hey%_thereyou're_a%rockstar%\nyo%there%", $matches);
    

        2
  •  4
  •   Greg    16 年前

    你在做一个贪婪的匹配-使用 ? 要使其不受约束,请执行以下操作:

    /%.*?%/
    

    /%.*?%/s
    
        3
  •  2
  •   Alix Axel    16 年前

    添加一个?在*之后:

    preg_match_all("/%.*?%/", "%hey%_thereyou're_a%rockstar%\nyo%there%", $matches);
    
        4
  •  1
  •   fresskoma    16 年前

    原因是那颗星很贪婪。也就是说,星号使正则表达式引擎尽可能频繁地重复前面的标记。你应该试试看?相反

        5
  •  1
  •   Tom Haigh    16 年前

    /%[^%]+%/ -这意味着在百分比符号之间,您只希望匹配不是百分比符号的字符。

    /%.+%/U ,因此它将捕获尽可能少的内容(我认为)。

        6
  •  1
  •   Pradeep Kumar Pradeep Kumar    16 年前

    推荐文章