簡體   English   中英

正則表達式在括號內抓取所有文本,而不是引號

[英]Regex grab all text between brackets, and NOT in quotes

我正在嘗試匹配{bracket}之間的所有文本,但是如果它在引號中則不匹配:例如:

$str = 'value that I {want}, vs value "I do {NOT} want" '

我的結果應該搶奪“想要”,但省略“不”。 我已經拼命搜索了stackoverflow的正則表達式,可以執行此操作,沒有運氣。 我已經看到了答案,允許我在引號之間但不在引號之間和括號中得到文本。 這甚至可能嗎?

如果是這樣,它是如何完成的?

到目前為止,這就是我所擁有的:

preg_match_all('/{([^}]*)}/', $str, $matches);

但遺憾的是,它只會將所有文本放在括號內,包括{NOT}

一次性完成這項工作非常棘手。 我甚至想讓它與嵌套括號兼容,所以讓我們也使用遞歸模式

("|').*?\1(*SKIP)(*FAIL)|\{(?:[^{}]|(?R))*\}

好吧,讓我們解釋一下這個神秘的正則表達式:

("|')                   # match eiter a single quote or a double and put it in group 1
.*?                     # match anything ungreedy until ...
\1                      # match what was matched in group 1
(*SKIP)(*FAIL)          # make it skip this match since it's a quoted set of characters
|                       # or
\{(?:[^{}]|(?R))*\}     # match a pair of brackets (even if they are nested)

在線演示

一些PHP代碼:

$input = <<<INP
value that I {want}, vs value "I do {NOT} want".
Let's make it {nested {this {time}}}
And yes, it's even "{bullet-{proof}}" :)
INP;

preg_match_all('~("|\').*?\1(*SKIP)(*FAIL)|\{(?:[^{}]|(?R))*\}~', $input, $m);

print_r($m[0]);

樣本輸出:

Array
(
    [0] => {want}
    [1] => {nested {this {time}}}
)

就個人而言,我會在兩次通過中處理此事。 第一個刪除雙引號之間的所有內容,第二個刪除你想要的文本。

也許這樣的東西:

$str = 'value that I {want}, vs value "I do {NOT} want" ';

// Get rid of everything in between double quotes
$str = preg_replace("/\".*\"/U","",$str);

// Now I can safely grab any text between curly brackets
preg_match_all("/\{(.*)\}/U",$str,$matches);

這里的工作示例:http: //3v4l.org/SRnva

暫無
暫無

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

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