簡體   English   中英

使用正則表達式從字符串返回第一個外部結果

[英]Return first outer result from a string, using regular expressions

我有以下字符串:

"{My {formatted {hi|hello}|formate{hi|hello} }  {option 1|option 2|option 3}}";

我想在“ {”和“}”括號之間找到結果。

結果也應該來自外層,而不是{hi|hello}而是:

"My {formatted {hi|hello}|formate{hi|hello} }  {option 1|option 2|option 3}"

您可以使用這種模式從不確定數量的嵌套括號中提取最外部的內容:

$pattern = '~{((?>[^{}]++|(?R))+)}~';

. 其中(?R)表示 這是一種遞歸方法。
如果需要在較大的表達式中將其用作子模式,則必須使用:
({((?>[^{}]++|(?-2))+)})因為(?-2)是相對於左側第二個捕獲組(此處是第一個捕獲組(?-2)的相對引用。

圖案細節:

 (             # first capturing group
   {           # literal {
   (           # second capturing group (what you are looking for)
     (?>       # atomic group
       [^{}]++ # all characters except { and }, one or more time
      |        # OR
       (?-2)   # repeat the first capturing group (second on the left)
     )+        # close the atomic group, repeated 1 or more time
   )           # close the second capturing group
   }           # literal }
 )             # close the first capturing group

/^{(.*)}$/將刪除第一個和最后一個{}

通過$var = preg_replace('/^{(.*)}$/', '$1', $your_text);

特別是也可以通過基本的字符串操作來實現,您可以將該正則表達式提升為/^[^{]*{(.*)}[^{]*$/ ,這可以讓您將chars放在所需的字符串前面,然后之后。 同樣,這可以通過使用substrstrrpos進行字符串操作本身來完成。

我認為您可以使用split Function.E然后可以使用Replace

http://php.net/manual/pt_BR/function.split.php

暫無
暫無

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

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