[英]How to grab code inside curly braces correctly?
我需要某種正則表達式來截取花括號中的部分代碼。 還有其他問題,但是我的有點不同。
將此代碼作為示例;
public function my_method($my_input) {
if(true == false) { $me = "Forever alone. :("; }
if(true == true) { $me = "No longer alone. :}"; }
if(false == false) { $me = ":{ - This is so Wrong."; }
}
並忽略“ public function my_method($ my_input) ”部分。 我怎么搶
if(true == false) { $me = "Forever alone. :("; }
if(true == true) { $me = "No longer alone. :}"; }
if(false == false) { $me = ":{ - This is so Wrong."; }
不會被字符串(和注釋等ofc)中的“ {”和“}”字符誤導?
我對正則表達式的了解非常有限,我很難實現這一目標。 :/
匹配括號是不應該使用正則表達式的典型示例之一(即使在字符串中沒有括號的情況下,它對於正則表達式來說也太復雜了)。
這是因為帶有嵌套括號的(正式)語言不是規則的,而是由上下文無關的語法表示的,這比簡單的正則表達式要復雜得多。 在非常高級別的正則表達式中,“不能計算任意大數”,即,它們不能識別哪個結束括號屬於哪個開始括號(只要您允許任意嵌套深度的括號,例如PHP(至少原則上是這樣) ))。
您最好獲取一些支持上下文無關語法的工具,甚至獲取一些已經編寫的PHP解析器。
為了自己提取函數,您可能應該只尋找關鍵字function
(或其他表示功能塊的關鍵字),然后轉到左括號( {
)。 然后,您可以逐個字符地進行下去,直到找到匹配的右括號( }
為止,同時跟蹤您當前是否在字符串,注釋或其他內容之內。
但是,我不希望您自己親自完成此任務,因為我可以想象照顧所有可能的極端情況非常麻煩...
我編寫了一個正則表達式,即使引號被反斜杠也可以在大多數情況下通過。 這是一個示例腳本。 我在正則表達式中提供了注釋,但請注意,我需要在正則表達式中的每個'都加反斜杠,因為我將其用作正則表達式本身的字符串定界符。
正則表達式是遞歸的,因此對嵌套括號的深度沒有限制。 但是,方括號中沒有錯誤(即沒有匹配的方括號),但是我想這是合乎邏輯的。
$str =
'
public function my_method($my_input) {
if(true == false) { $me = "Forever alone. :("; }
if(true == true) { $me = "No longer alone. :}"; }
if(true == true) { $me = \'No longer alone. :}\'; }
if(true == true) { $me = \'No longer \\\' alone. :}\'; }
if(false == false) { $me = ":{ - This is so Wrong."; }
}
public function my_method($my_input) {
if(true == false) { $me = "Forever happy. :("; }
if(true == true) { $me = "No longer happy. :}"; }
if(true == true) { $me = \'No longer happy. :}\'; }
if(true == true) { $me = \'No longer \\\' happy. :}\'; }
if(false == false) { $me = ":{ - This is so Wrong."; }
}
';
preg_match_all(
'/
{ # opening {
( # matching parentheses
(?: # non matching parentheses
(?: # non matching parentheses
[^{}"\']+ # anything but { } " and \'
| # or
" # opening "
(?: # non matching parentheses
[^"\\\]* # anything but " and \
| # or
\\\" # a \ followed by a "
)* # as often as possible
" # closing "
| # or
\' # opening \'
(?: # non matching parentheses
[^\'\\\\]* # anything but \' and \
| # or
\\\\\' # a \ followed by a \'
)* # as often as possible
\' # closing \'
)* # as often as possible
| # or
(?R) # repeat the whole pattern
)* # as often as possible
) # close matching parentheses
} # closing }
/xs',
$str,
$matches
);
print_r($matches);
正則表達式不是正確的工具-有關更多詳細信息,請參見@phimuemue的答案 。
不過,您可以在腳本中使用PHP自己的令牌生成器 。 但是,它不會簡單地為您提供“某個塊內的內容”,而是給您塊內的令牌。 根據您要執行的操作,您需要從令牌中重構源代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.