[英]How to apply regular expressions to get a number from a dynamic string
I have a variable that can contain a few variations, it also contains a number which can be any number.我有一个可以包含一些变化的变量,它还包含一个可以是任何数字的数字。
The variations:变化:
($stuksprijs+9.075);
($stuksprijs-9.075);
($stuksprijs*9.075);
($m2+9.075);
($m2-9.075);
($m2*9.075);
($o+9.075);
($o-9.075);
($o*9.075);
These are the only variations except for the numbers in it, they can change.这些是除了其中的数字之外的唯一变化,它们可以改变。 And I need that number.我需要那个号码。
So there can be:所以可以有:
($m2+5);
or或者
($o+8.25);
or或者
($stuksprijs*3);
How can I get the number from those variations?我怎样才能从这些变化中得到数字? How can I get the 9.075 or 5 or 8.25 or 3 from my above examples with regular expression?如何使用正则表达式从上述示例中获得 9.075 或 5 或 8.25 或 3?
I am trying to fix this with PHP, my variable that contains the string is: $explodeberekening[1]
我正在尝试使用 PHP 解决此问题,包含该字符串的变量是: $explodeberekening[1]
I read multiple regex tutorials and got it to work for a single string that never changes, but how can I write a regex to get the number from above variations?我阅读了多个正则表达式教程,并让它适用于一个永远不会改变的字符串,但是我如何编写一个正则表达式来从上述变化中获取数字?
As per my comment, which seems to have worked, you can try:根据我的评论,这似乎有效,您可以尝试:
^\(\$(?:stuksprijs|m2|o)[+*-](\d+(?:\.\d+)?)\);$
The number is captured in the 1st capture group.该号码在第一个捕获组中捕获。 See the online demo .请参阅在线演示。
A quick breakdown:快速细分:
^
- Start string anchor. ^
- 开始字符串锚。\(\$
- Literally match "($". \(\$
- 字面上匹配“($”。(?:
- Open a non-capture group to list alternation: (?:
- 打开一个非捕获组以列出交替:
stuksprijs|m2|o
- Match one of these literal alternatives. stuksprijs|m2|o
- 匹配这些文字替代品之一。)
- Close non-capture group. )
- 关闭非捕获组。[+*-]
- Match one of the symbols from the character-class. [+*-]
- 匹配字符类中的符号之一。(
- Open 1st capture group: (
- 打开第一个捕获组:
\d+
- 1+ digits. \d+
- 1+ 位。(?:\.\d+)?
- Extra optional non-capture group to match a literal dot and 1+ digits. - 额外的可选非捕获组以匹配文字点和 1+ 数字。)
- Close 1st capture group. )
- 关闭第一个捕获组。\);
- Literally match ");". - 字面上匹配“);”。$
- End string anchor. $
- 结束字符串锚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.