Php regex-单位旁边的浮点数字的模式是什么
基本上我想在str中匹配一个简单的东西,但只想返回匹配的第一部分。这就是我想看的 Jo 4.5盎司感冒和流感饮料 我想做的是返回4.5,但只有当比赛之后有一个变化的once单位 这是我的猜测Php regex-单位旁边的浮点数字的模式是什么,php,regex,Php,Regex,基本上我想在str中匹配一个简单的东西,但只想返回匹配的第一部分。这就是我想看的 Jo 4.5盎司感冒和流感饮料 我想做的是返回4.5,但只有当比赛之后有一个变化的once单位 这是我的猜测 /([0-9]*\.?[0-9])(?:[\s+][o(?<=\.)z(?<=\.)|ounce]?=\s)/i 但是当我运行它的时候,我得到了 $matches = null; $returnValue = preg_match('/([0-9]*\.?[0-9])(?:[\s+][o(?&
/([0-9]*\.?[0-9])(?:[\s+][o(?<=\.)z(?<=\.)|ounce]?=\s)/i
但是当我运行它的时候,我得到了
$matches = null;
$returnValue = preg_match('/([0-9]*\.?[0-9])(?:[\s+][o(?<=\.)z(?<=\.)|ounce]?=\s)/i', 'Jo 4.5 Oz cold and flu stuff to drink.', $matches);
$matches=null;
$returnValue=preg\u match('/([0-9]*\.?[0-9])(?:[\s+][o(?我认为它可能比您在那里尝试的要简单一些。尝试一下这个表达式:
\s[\d]+.{1}[\d]+\s*(oz|ounce|o.z.|oz.)
或使用完整的php:
$test_string = 'Jo 4.5 Oz cold and flu stuff to drink.';
$returnValue = preg_match('/\s[\d]+.{1}[\d]+\s*(oz|ounce|o.z.|oz.)/i', $test_string, $matches);
编辑
如果要检查他们是否使用。或,可以使用:
\d+(.|,){1}\d+\s*(ounce|o\.?z\.?)
或
编辑2
如果需要命名模式,请尝试以下操作:
$returnValue = preg_match('/(?P<amount>\d+(.|,){1}\d+)\s*(?P<unit>(ounce|o\.?z\.?))/ix', $test_string, $matches);
print_r($matches);
然后您需要一个不太复杂的模式,如:
preg_match('/
(\d+(\.\d+)?) # float
\s* # optional space
( ounce | o\.? z\.? ) # "ounce" or "o.z." or "oz"
/ix', # make it case insensitive
$string, $matches);
然后查看结果$matches[1]
,或者通过将余数括在(?=…)
中,使其成为一个断言。没有,但是/([\d]+.{1}[\d]+)(?:\s*oz |盎司| oz.)/我在$match[1]上做了…但是有更好的方法来做到这一点吗..如果是打字错误..嗯,对不起,我忘记删除了(检查空格)。不确定你所说的“一种更好的方式来表达观点……以防拼写错误”——你的意思是如果他们用逗号来代替吗?你可以使用:\d+(.|,){1}\d+\s*(盎司| o\.?z\.?)然后确保使用ix来忽略大小写和扩展……是的,这就是我得到的地方。/([\d]+.{1}[\d]+)(?:\s*o\.?z\.?)/我……但我觉得你的更干净
$returnValue = preg_match('/(?P<amount>\d+(.|,){1}\d+)\s*(?P<unit>(ounce|o\.?z\.?))/ix', $test_string, $matches);
print_r($matches);
Array
(
[0] => 4.5 Oz
[amount] => 4.5
[1] => 4.5
[2] => .
[unit] => Oz
[3] => Oz
[4] => Oz
)
preg_match('/
(\d+(\.\d+)?) # float
\s* # optional space
( ounce | o\.? z\.? ) # "ounce" or "o.z." or "oz"
/ix', # make it case insensitive
$string, $matches);