括号内的正则表达式

时间:2018-03-21 07:00:53

标签: php regex

我需要在括号内得到浮点数。

我尝试了这个'([0-9]*[.])?[0-9]+' ,但它在第一个例子中返回了第一个数字,如6。 我也试过这个

'/\((\d+)\)/'

但它返回0。 请注意,我需要提取的数字为int或float。

你可以帮助

吗?

enter image description here

4 个答案:

答案 0 :(得分:0)

你可以逃脱括号:

$str = 'Serving size 6 pieces (41.5)';
if (preg_match('~\((\d+.?\d*)\)~', $str, $matches)) {
    print_r($matches);
}

输出:

Array
(
    [0] => (41.5)
    [1] => 41.5
)

正则表达式:

\(    # open bracket
 (    # capture group
  \d+ # one or more numbers
  .?  # optional dot
  \d* # optional numbers
 )    # end capture group
\)    # close bracket

您也可以使用它来获得点后的一位数字:

'~\((\d+.?\d?)\)~'

答案 1 :(得分:0)

由于您还需要匹配括号,您需要在正则表达式中添加()

$str = 'Serving size 6 pieces (40)';
$str1 = 'Per bar (41.5)';
preg_match('#\(([0-9]*[.]?[0-9]+)\)#', $str, $matches);
print_r($matches);

preg_match('#\(([0-9]*[.]?[0-9]+)\)#', $str1, $matches);
print_r($matches);

输出:

Array
(
    [0] => (40)
    [1] => 40
)
Array
(
    [0] => (41.5)
    [1] => 41.5
)

DEMO

答案 2 :(得分:0)

您需要转义括号

preg_match('/\((\d+(?:\.\d+)?)\)/', $search, $matches);

解释

\(    escaped bracket to look for
(     open subpattern
\d    a number
+     one or more occurance of the character mentioned
(     open Group
?:    dont save data in a subpattern
\.    escaped Point
\d    a number
+     one or more occurance of the character mentioned
)     close Group
?     one or no occurance of the Group mentioned
)     close subpattern
\)    escaped closingbracket to look for

匹配数字 1, 1.1, 11, 11.11, 111, 111.111但不是.1,。

https://regex101.com/r/ei7bIM/1

答案 3 :(得分:0)

您可以匹配左括号,使用\K重置报告的匹配的起点,然后匹配您的值:

\(\K\d+(?:\.\d+)?(?=\))

那将匹配:

  • \(匹配(
  • \K重置报告的匹配的起点
  • \d+匹配一个或多个数字
  • (?: Non capturing group
    • \.\d+匹配一个点和一个或多个数字
  • )?关闭非捕获组并将其设为可选
  • (?=断言以下内容的积极前瞻
    • \)匹配)
  • )关闭posal lookahead

Demo php