簡體   English   中英

如何使用正則表達式排除兩個大括號之間的文本?

[英]How to exclude text between two curly brackets with regex?

我是正則表達式的新手,我有這樣的文字:

test{{this 不應該被選中,大括號也是}} 但這個 { 或 } 應該被選中。 所以我想排除左大括號和右大括號之間的所有文本。

我想要這個結果

“測試”

“但應該選擇這個 { 或 }。所以我想排除左大括號和右大括號之間的所有文本。”

這是我使用的表達方式:

$p = '/[a-zA-Z0-9#\' ]+(?![^{{]*}})/';

但這不包括單個大括號。
我想知道如何在文本中包含單個大括號並僅排除兩個大括號之間的文本
請你能給我一些關於正則表達式的好文檔嗎? 我想了解更多關於這方面的信息。

(?:^|(?:}}))(.+?)(?:$|{{)

試試看: https : //regex101.com/r/2Xy7gU/1/
這里發生了什么:

  • (?:^|(?:}})) - 它以字符串開頭或 }}
  • (.+?) - 匹配所有內容(非貪婪)
  • (?:$|{{) - 匹配必須以字符串結尾或 {{

你想要的(沒有括號)在第一組中。

輸入(我將字符串加倍以達到效果):

$string = 'test{{this should not be selected and the curly brackets too}} but this one { or } should be selected. So I want to exclude all text between an opening and closing curly brackets. test{{this should not be selected and the curly brackets too}} but this one { or } should be selected. So I want to exclude all text between an opening and closing curly brackets.';

方法 #1 preg_split()

var_export(preg_split('/{{[^}]*}}/', $string, 0, PREG_SPLIT_NO_EMPTY));
// Added the fourth param in case the input started/ended with a double curly substring.

方法#2 preg_match_all()

var_export(preg_match_all('/(?<=}{2}|^)(?!{{2}).*?(?={{2}|$)/s', $string, $out) ? $out[0] : []);

輸出(無論哪種方式):

array (
  0 => 'test',
  1 => ' but this one { or } should be selected. So I want to exclude all text between an opening and closing curly brackets. test',
  2 => ' but this one { or } should be selected. So I want to exclude all text between an opening and closing curly brackets.',
)

preg_split()將雙卷曲包裹的子字符串視為“分隔符”並在其上拆分完整字符串。


preg_match_all()方法模式...模式演示這使用正向后視和正向前瞻,兩者都尋找雙卷曲或字符串的開始/結束。 它在中間使用負前瞻以避免在新行的開頭匹配不需要的雙卷曲字符串。 最后,模式末尾的s修飾符將允許. 匹配換行符。

使用preg_replace並將所有出現的\\{\\{[^\\}]*\\}\\}替換為空字符串。

示例: http : //www.regextester.com/?fam=97777

解釋:

\{      - {
\{      - {
[^\}]*  - everything except }
\}      - }
\}      - }

2個選項:

  • 簡單:只需將 {{ }} 之間的塊視為拆分模式
    $validblocks = preg_split("/{{[\\w .]+}}/", $str);
  • 復雜:使用組並首先捕獲被拒絕的模式,然后剩下的:
    (?<novalid>{{[\\w ]+}})|(?<valid>{|[\\w .]*|})
    之后隨心所欲地管理它。 此處示例: https : //regex101.com/r/SK729o/2

暫無
暫無

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

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