如何从字符串中获取括在括号中的数字?
How to get a number wrapped in parentheses from a string?
我有这个代码
$string = "23 asdasdasdasd.sma(33) asda sdas asd 23 2 3 54232 23d asd";
$reg = "??";
preg_match($reg, $string, $matches);
var_dump($matches);
我要获取这个号码:33
.
我认为正则表达式应该是这样的
$reg = "\(([0-9]+)\)";
尝试使用模式 \((\d+)\)
:
preg_match("/\((\d+)\)/", $string, $matches);
第一个捕获组将包含括号内的数字。
您也可以使用 \(\K\d+(?=\))
那将匹配:
\( # Match (
\K # Reset the starting point of the reported match
\d+ # Match one or more digits
(?=\)) # Positive lookahead that asserts what follows is )
$reg = '/\(\K\d+(?=\))/';
号码会在$matches[0];
因为您在代码中调用 preg_match()
并且您的输入数据只有一个可用的目标编号,所以您可以准确地使用此 fastest/briefest 模式:
~\(\K\d+~
(Pattern Demo)(5 个步骤,没有捕获组,没有环视)
模式分解:
~ #pattern delimiter
\( #match (
\K #restart the fullstring match (forget previously matched characters)
\d+ #match one or more digits greedily
~ #pattern delimiter
* 需要说明的是,我想声明我的模式假定紧跟在 (
之后的数字将跟在 )
之后。这就是示例输入提供的内容。
如果 )
需要匹配以保持准确性,那么捕获组(Tim 的方式)将是下一个最有效的方式。所有使用环视的正确模式都将比不使用环视的正确模式慢。
我有这个代码
$string = "23 asdasdasdasd.sma(33) asda sdas asd 23 2 3 54232 23d asd";
$reg = "??";
preg_match($reg, $string, $matches);
var_dump($matches);
我要获取这个号码:33
.
我认为正则表达式应该是这样的
$reg = "\(([0-9]+)\)";
尝试使用模式 \((\d+)\)
:
preg_match("/\((\d+)\)/", $string, $matches);
第一个捕获组将包含括号内的数字。
您也可以使用 \(\K\d+(?=\))
那将匹配:
\( # Match ( \K # Reset the starting point of the reported match \d+ # Match one or more digits (?=\)) # Positive lookahead that asserts what follows is )
$reg = '/\(\K\d+(?=\))/';
号码会在$matches[0];
因为您在代码中调用 preg_match()
并且您的输入数据只有一个可用的目标编号,所以您可以准确地使用此 fastest/briefest 模式:
~\(\K\d+~
(Pattern Demo)(5 个步骤,没有捕获组,没有环视)
模式分解:
~ #pattern delimiter
\( #match (
\K #restart the fullstring match (forget previously matched characters)
\d+ #match one or more digits greedily
~ #pattern delimiter
* 需要说明的是,我想声明我的模式假定紧跟在 (
之后的数字将跟在 )
之后。这就是示例输入提供的内容。
如果 )
需要匹配以保持准确性,那么捕获组(Tim 的方式)将是下一个最有效的方式。所有使用环视的正确模式都将比不使用环视的正确模式慢。