gpt4 book ai didi

php - 正则表达式:如何捕获以一组匹配的字符开头的组

转载 作者:行者123 更新时间:2023-12-04 08:40:27 26 4
gpt4 key购买 nike

这是我想拆分为数组的一串字符:

35g walnut halves A handful of thyme leaves 200g portobello mushrooms 200g white mushrooms 200g chifferini pasta 100g Petit Brebis sheep's cheese 40g honey
我想用 preg_split从字符串中提取各个成分。一个单独的成分开始于:
  • 由数字加上字符 g 定义的数量
  • 一个字符序列,例如 A handful

  • 到目前为止,我有这个正则表达式模式 ([0-9]+g|A handful)它正确地找到了字符串中的断点,但不包括整个成分描述。我需要捕获组包含其余字符,直到下一场比赛。
    为了获得数组返回,我使用了这个 PHP: preg_split("/([0-9]+g|A handful)/", $ingredients_str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY)所需的输出是:
    [
    0 => 35g walnut halves
    1 => A handful of thyme leaves
    2 => 200g portobello mushrooms
    etc..
    ]
    regex 101

    最佳答案

    您可以使用 preg_match_all提取所有描述:

    preg_match_all('~(?:\d+g|A handful).*?(?=\s*(?:\d+g|A handful|$))~s', $str, $matches)
    regex demo .
    详情
  • (?:\d+g|A handful) - 1+ 位后跟 gA handful
  • .*? - 任何零个或多个字符,尽可能少
  • (?=\s*(?:\d+g|A handful|$)) - 直到字符串中紧跟 0+ 空格后跟 1+ 数字和 g 的位置, 或 A handful或字符串结尾。

  • PHP demo :
    $re = '/(?:[0-9]+g|A handful).*?(?=\s*(?:[0-9]+g|A handful|$))/s';
    $str = '35g walnut halves A handful of thyme leaves 200g portobello mushrooms 200g white mushrooms 200g chifferini pasta 100g Petit Brebis sheep\'s cheese 40g honey';
    if (preg_match_all($re, $str, $matches)) {
    print_r($matches[0]);
    }
    输出:
    Array
    (
    [0] => 35g walnut halves
    [1] => A handful of thyme leaves
    [2] => 200g portobello mushrooms
    [3] => 200g white mushrooms
    [4] => 200g chifferini pasta
    [5] => 100g Petit Brebis sheep's cheese
    [6] => 40g honey
    )
    一个 preg_split解决方案可能看起来像
    $re = '/(?!^)\b(?=[0-9]+g|A handful)/';
    $str = '35g walnut halves A handful of thyme leaves 200g portobello mushrooms 200g white mushrooms 200g chifferini pasta 100g Petit Brebis sheep\'s cheese 40g honey';
    print_r(preg_split($re, $str));
    demo online .这里,
  • (?!^) - 匹配不在字符串开头的位置
  • \b - 字边界
  • (?=[0-9]+g|A handful) - 紧跟 1+ 位数字然后是 g 的位置或 A handful子串。
  • 关于php - 正则表达式:如何捕获以一组匹配的字符开头的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64595316/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com