本文介绍了正则表达式数字字符串数字字符串循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的字符串是:
$str='Move 10 Casio Watch 20 Apple Iphone 100 Apple Macbook to store';
我用过:
preg_match_all('| ([0-9]+) (.*) |', $str, $matches);
但它只匹配产品名称的第一个字母.
But it only matches the first letter of the product name.
我的结果:
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
)
)
推荐答案
Regex: \d+ \K(?: ?[AZ][az]+)+
详情:
\d+
匹配一次到无限次之间的数字\K
重置报告匹配的起点(?:)
非捕获组?
匹配 0 次和 1 次之间的空格字符[A-Z]
匹配大写字符[a-z]+
匹配一次和无限次之间的小写字符(?:)+
在一次和无限次之间重复匹配
\d+
matches a digit between one and unlimited times\K
resets the starting point of the reported match(?:)
non-capturing group?
Match space char between zero and one times[A-Z]
match upper case char[a-z]+
match lower case char between one and unlimited times(?:)+
repeat matching between one and unlimited times
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
)
这篇关于正则表达式数字字符串数字字符串循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!