单位旁边的浮点数字的模式是什么


what is the pattern for floating point digit next to unit

基本上我想在str中匹配一个简单的东西,但只想返回这个匹配的第一部分。这就是我想要查找的。

Jo 4.5 Oz感冒和流感的饮料。

我想做的是返回4.5,但只有当比赛之后有一个单位的变化时。

这是我的猜测

/([0-9]*'.?[0-9])(?:['s+][o(?<='.)z(?<='.)|ounce]?='s)/i

匹配时:

4.5oz
4.5 oz
4.5 o.z.
4.5 oz.
4.5         oz.
4.5ounce
4.5Ounce
4.5 Oz.

但到目前为止,当我运行它时,我得到了。

$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);

任何帮助都会很棒。非常感谢。干杯-Jeremy

然后您需要一个不那么复杂的模式,如:

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],或者将余数封装在(?=...)中,使其成为断言

我认为它可能比您在那里尝试的要简单一点。试试这个表达式:

'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);

编辑

如果你想检查他们是否使用。或者a,你可以使用:

'd+(.|,){1}'d+'s*(ounce|o'.?z'.?)

 $returnValue = preg_match('/'d+(.|,){1}'d+'s*(ounce|o'.?z'.?)/ix', $test_string, $matches);

编辑2

如果你想要命名模式,试试这个:

$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
)