首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Regex:如何从匹配的字符集开始捕获组

Regex:如何从匹配的字符集开始捕获组
EN

Stack Overflow用户
提问于 2020-10-29 16:28:53
回答 1查看 52关注 0票数 2

下面是我想要分割成一个数组的字符串:

代码语言:javascript
复制
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

到目前为止,我有一个regex模式([0-9]+g|A handful),它正确地找到字符串中的断线,但不包括整个成分描述。我需要捕捉组包括其余的字符,直到下一次匹配。

为了获得数组返回,我使用了以下PHP:

preg_split("/([0-9]+g|A handful)/", $ingredients_str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY)

期望的输出是:

代码语言:javascript
复制
[
  0 => 35g walnut halves
  1 => A handful of thyme leaves
  2 => 200g portobello mushrooms
  etc..
]

请参阅regex 101

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-29 16:33:29

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

代码语言:javascript
复制
preg_match_all('~(?:\d+g|A handful).*?(?=\s*(?:\d+g|A handful|$))~s', $str, $matches)

regex演示

详细信息

  • (?:\d+g|A handful) - 1+数字后面跟着gA handful
  • .*? -任何零或多个字符,尽可能少
  • (?=\s*(?:\d+g|A handful|$)) -直到字符串中的一个位置,该位置紧跟在0+空格后面,后面跟着1+位数和g,或者是A handful或字符串的末尾。

PHP演示

代码语言:javascript
复制
$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]);
}

输出:

代码语言:javascript
复制
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解决方案可能看起来像

代码语言:javascript
复制
$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));

在线演示。这里,

  • (?!^) -匹配不位于字符串开头的位置。
  • \b -字边界
  • (?=[0-9]+g|A handful) -一个紧跟在1+数字后面的位置,然后是gA handful子字符串。
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64595316

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档