Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在字符串中查找特定的浮点数?_Php_Regex - Fatal编程技术网

Php 在字符串中查找特定的浮点数?

Php 在字符串中查找特定的浮点数?,php,regex,Php,Regex,我想使用正则表达式从字符串中查找特定的浮点数。 串 我要找到这个的唯一数字是0.30。 我尝试了很多模式,但它们都返回字符串中的整个浮点数,其中一些根本不起作用 [-+]?([0-9]*\,)?[0-9]+ \d+(?:\.\d+)? 我也试过了 floatval() 但是它也不起作用你可以用空格包围一个数字(如果你正在寻找的话): 说明: (?:^|\s) # the begining of the string or a white character \K # re

我想使用正则表达式从字符串中查找特定的浮点数。

我要找到这个的唯一数字是0.30。 我尝试了很多模式,但它们都返回字符串中的整个浮点数,其中一些根本不起作用

[-+]?([0-9]*\,)?[0-9]+
\d+(?:\.\d+)?
我也试过了

floatval()

但是它也不起作用

你可以用空格包围一个数字(如果你正在寻找的话):

说明:

(?:^|\s)   # the begining of the string or a white character
\K         # reset all that is matched before
\d+        # digit one or more times
(?:\.\d+)? # optional dot and digits
(?=\s|$)   # followed by a white character or the end of the string

您可以使用以下选项将数字用空格包围(如果您正在查找):

说明:

(?:^|\s)   # the begining of the string or a white character
\K         # reset all that is matched before
\d+        # digit one or more times
(?:\.\d+)? # optional dot and digits
(?=\s|$)   # followed by a white character or the end of the string
试试这个:

(?<!\$)\b[-+]?\d+\.\d+\b(?!%)
(?
它匹配一个带有小数点的数字,但前面不带
$
,后面不带
%

请参见尝试以下操作:

(?<!\$)\b[-+]?\d+\.\d+\b(?!%)
(?
它匹配一个带有小数点的数字,但前面不带
$
,后面不带
%


请参见

如果字符串格式是静态的(例如,它没有更改),那么为什么要使用正则表达式来查找它

您要查找的字符串组件可以通过基于空格分解字符串来轻松定位,而且不需要太多努力:

$string = "202-715-1278 2 0.01% 0.30 0.00% $0.00 0.00%";
$parts = explode(' ', $string);
echo $parts[3]; // 0.30

此外,如果您使用正则表达式,任何开发人员遇到您的代码都必须花时间理解它-除非您对它进行了很好的文档记录!

如果字符串格式是静态的(例如,它没有改变),那么为什么要使用正则表达式来查找它呢

您要查找的字符串组件可以通过基于空格分解字符串来轻松定位,而且不需要太多努力:

$string = "202-715-1278 2 0.01% 0.30 0.00% $0.00 0.00%";
$parts = explode(' ', $string);
echo $parts[3]; // 0.30

此外,如果您使用正则表达式,任何开发人员遇到您的代码都必须花时间理解它-除非您将其记录好!

模式是什么?您是否总是尝试获取第四个数字?只有第二个是浮点数?我尝试获取这个0.30,没有%或$这仍然不清楚。第一个没有%或$的数字是2。如果希望始终为0.30,只需执行$var=0.30在
上分解字符串即可
然后对元素使用正则表达式?@AurelioDeRosa第一个数字2不是浮点数,0.30不是固定数字模式是什么?您是否总是尝试获取第四个数字?只有第二个是浮点数?我正在尝试获取这一个0.30,它没有%或$这仍然不清楚。第一个数字没有%或者$2。如果希望始终为0.30,只需执行$var=0.30在
上分解字符串即可
然后对元素使用正则表达式?@AurelioDeRosa第一个数字2不是浮点数,0.30不是固定数number@Dr.Neo:Normal,rubular代表ruby而不是php。ruby不支持
\K
功能。请改用。@Dr.Neo:Normal,rubular代表ruby而不是php。ruby不支持
\K
功能e、 改用。