簡體   English   中英

如何從字符串中得到一個用括號括起來的數字?

[英]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];

PHP演示

因為您正在代碼中調用preg_match() ,並且輸入數據只有一個目標編號可用,所以您可以准確地使用這種最快/最簡單的模式:

~\\(\\K\\d+~模式演示 )(5個步驟&沒有捕獲組&沒有環顧四周)

模式細分:

~        #pattern delimiter
\(       #match (
\K       #restart the fullstring match (forget previously matched characters)
\d+      #match one or more digits greedily
~        #pattern delimiter

*清楚一點,我想指出的是,我的模式假設緊隨(將會緊跟a ) 這就是示例輸入所提供的。

如果)要匹配,以保持精度,然后捕獲組(Tim的方式)將是下一個最有效的方式。 使用環視的所有正確模式都將比不使用環視的正確模式慢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM