[英]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]+)\)";
您也可以使用\\(\\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()
,並且輸入數據只有一個目標編號可用,所以您可以准確地使用這種最快/最簡單的模式:
~\\(\\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.