[英]How to use regex to get multiple occurrences of formula in PHP
I want to extract each arithmetic formula from this string:我想从这个字符串中提取每个算术公式:
+100*25-30
I used this regex:我使用了这个正则表达式:
preg_match_all("/(([\*\+\-\/])([0-9]+\.?[0-9]*))+/", "+100*25-30", $match);
It is capturing only last occurrence which is -30 but if I enter space before operator like this: +100 *25 -30, it is capturing all correctly, but I should do it without space.它只捕获最后一次出现的 -30 但如果我在这样的运算符之前输入空格:+100 *25 -30,它会正确捕获所有内容,但我应该在没有空格的情况下进行。 How to do it?
怎么做?
The (([\*\+\-\/])([0-9]+\.?[0-9]*))+
pattern is an example of a repeated capturing group . (([\*\+\-\/])([0-9]+\.?[0-9]*))+
模式是重复捕获组的示例。 Since it matches the whole +100*25-30
string capturing each pair of the match operator with the number after it, only the last occurrence captured is stored in the Group 1 (that is -30
).由于它将捕获每对匹配运算符的整个
+100*25-30
字符串与其后面的数字相匹配,因此只有捕获的最后一个匹配项存储在组 1 中(即-30
)。
You can use您可以使用
preg_match_all("/([*+\/-]?)([0-9]+\.?[0-9]*)/", "+100*25-30", $match)
See the PHP demo .请参阅PHP 演示。 Alternatively,
preg_match_all("/([*+\/-]?)([0-9]*\.?[0-9]+)/", "+100*25-30", $match)
.或者,
preg_match_all("/([*+\/-]?)([0-9]*\.?[0-9]+)/", "+100*25-30", $match)
。
See also the regex demo.另请参阅正则表达式演示。
Details :详情:
([*+\/-]?)
- Group 1: an optional *
, +
, /
or -
char ([*+\/-]?)
- 第 1 组:可选*
、 +
、 /
或-
字符([0-9]*\.?[0-9]+)
- Group 2: zero or more digits, an optional .
([0-9]*\.?[0-9]+)
- 第 2 组:零个或多个数字,可选的.
and one or more digits.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.