正则表达式数字字符串数字字符串循环

时间:2018-08-30 02:49:20

标签: regex

我的字符串是:

$str='Move 10 Casio Watch 20 Apple Iphone 100 Apple Macbook to store';

我用过:

preg_match_all('| ([0-9]+) (.*) |', $str, $matches);

但是它仅与产品名称的首字母匹配。

我的结果:

Array
(
    [0] => Array
        (
            [0] =>  10 Casio 
            [1] =>  20 Apple 
            [2] =>  100 Apple 
        )

    [1] => Array
        (
            [0] => 10
            [1] => 20
            [2] => 100
        )

    [2] => Array
        (
            [0] => Casio
            [1] => Apple
            [2] => Apple
        )
)

1 个答案:

答案 0 :(得分:1)

正则表达式\d+ \K(?: ?[A-Z][a-z]+)+

详细信息

  • \d+匹配一个无限制次数的数字
  • \K重置报告的比赛的起点
  • (?:)非捕获组
  • ?匹配空格字符0到1次
  • [A-Z]匹配大写字符
  • [a-z]+匹配一次和无限次的小写字符
  • (?:)+在一次和无限次之间重复匹配

PHP代码

$str = 'Move 10 Casio Watch 20 Apple Iphone 100 Apple Macbook to store';
preg_match_all("~\d+ \K(?: ?[A-Z][a-z]+)+~", $str, $matches);
print_r($matches[0]);

输出:

Array
(
    [0] => Casio Watch
    [1] => Apple Iphone
    [2] => Apple Macbook
)