我想獲得數組格式的子字符串,它位於input()
的內部。我使用preg_match
,但無法獲得整個表達式。它在第一個)
停止。我如何匹配整個子字符串?謝謝。如何從字符串中捕獲數組格式的子字符串
$input="input([[1,2,nc(2)],[1,2,nc(1)]])";
preg_match('@^([^[]+)?([^)]+)@i',$input, $output);
期望是:
'[[1,2,nc(2)],[1,2,nc(1)]]'
我想獲得數組格式的子字符串,它位於input()
的內部。我使用preg_match
,但無法獲得整個表達式。它在第一個)
停止。我如何匹配整個子字符串?謝謝。如何從字符串中捕獲數組格式的子字符串
$input="input([[1,2,nc(2)],[1,2,nc(1)]])";
preg_match('@^([^[]+)?([^)]+)@i',$input, $output);
期望是:
'[[1,2,nc(2)],[1,2,nc(1)]]'
這種模式匹配所需的字符串(也與啓動字≠ '輸入':
@^(.+?)\((.+?)\)[email protected]
^(.+?) => find any char at start (ungreedy option)
\) => find one parenthesis
(.+?) => find any char (ungreedy option) => your desired match
\) => find last parenthesis
試試這個:
$input="input([[1,2,nc(2)],[1,2,nc(1)]])";
preg_match('/input\((.*?\]\])\)/',$input,$matches);
print_r($matches);
$匹配[1]將包含你需要整個結果。希望這可以工作。
你想要它純粹是一個字符串?使用這個簡單的正則表達式:
preg_match('/\((.*)\)$/',$input,$matches);
的無其他答案有效/準確地解答了您的問題:
爲了最快精確圖案,使用:
$input="input([[1,2,nc(2)],[1,2,nc(1)]])";
echo preg_match('/input\((.*)\)/i',$input,$output)?$output[1]:'';
// notice index^
或者說,通過避免捕獲組使用少50%的內存,使用稍慢的圖案:
$input="input([[1,2,nc(2)],[1,2,nc(1)]])";
echo preg_match('/input\(\K(.*)(?=\))/i',$input,$output)?$output[0]:'';
// notice index^
這兩種方法都將提供相同的輸出:[[1,2,nc(2)],[1,2,nc(1)]]
使用貪婪*
量詞允許模式移動通過嵌套括號並匹配整個預期子。
在第二種模式中,\K
重置匹配的起始點,並且(?=\))
是確保整個子串匹配而不包括尾隨右閉括號的正向預測。
編輯:所有這一切正則表達式卷積一邊,因爲你知道你想要的子被包裹在input(
和)
,最好的,最簡單的方法是一種非正則表達式一個...
$input="input([[1,2,nc(2)],[1,2,nc(1)]])";
echo substr($input,6,-1);
// output: [[1,2,nc(2)],[1,2,nc(1)]]
完成。
@Gamsh我加了一個更簡單的方法。看我的編輯。 – mickmackusa