2016-04-24 26 views
3

我有一個string,其中包含一些文本,後面跟着一些帶有不同內容(可能爲空)的括號。我需要它的內容提取最後支架:匹配最後一個支架

atext[d][][ef] // should return "[ef]" 
other[aa][][a] // should return "[a]" 
xxxxx[][xx][x][][xx] // should return "[xx]" 
yyyyy[] // should return "[]" 

我已經調查RegexOptions.RightToLeftlazy vs greedy matching讀了,但我不能爲我的生命得到這樣一個權利。

+0

【檢查】(https://regex101.com/r/bZ9tP4/1) – rock321987

回答

3

此正則表達式將工作

.*(\[.*\]) 

Regex Demo

更高效和非貪婪版本

.*(\[[^\]]*\]) 

C#代碼

string input = "atext[d][][ef]\nother[aa][][a]\nxxxxx[][xx][x][][xx]\nyyyyy[]"; 
string pattern = "(?m).*(\\[.*\\])"; 
Regex rgx = new Regex(pattern); 

Match match = rgx.Match(input); 

while (match.Success) 
{ 
    Console.WriteLine(match.Groups[1].Value); 
    match = match.NextMatch(); 
} 

Ideone Demo

它可能會嵌套[]或不平衡[]

+1

,包括嵌套的'[]'情況下,你做'*(\ [* \。])'的https: //regex101.com/r/bZ9tP4/2 – dnit13

+0

@ dnit13可以做,但它也不會是正確的..eg ''[aa [bb]]',你會得到'[bb]',但根據我的輸出應該是'[aa [bb]]',因爲它不是最後一個的嵌套支架。它只是一個看起來雖然 – rock321987

+0

@ dnit13我已經添加了正則表達式的修改版本 – rock321987

0

或者意想不到的效果,你可以使用一個類似的功能,扭轉字符串:

public static string Reverse(string s) 
{ 
    char[] charArray = s.ToCharArray(); 
    Array.Reverse(charArray); 
    return new string(charArray); 
} 

然後你可以執行簡單的正則表達式搜索,只查找第一個[someText]組,或者只是使用for循環遍歷,然後停止首先到達]

0

隨着負前瞻:

\[[^\]]*\](?!\[) 

這是比較有效的,靈活的,沒有邪惡.*。這也適用於包含多個實例的較長文本。

Regex101 demo here

0

for .NET的正確的方法確實是使用正則表達式選項RightToLeft用適當的方法Regex.Match(String, String, RegexOptions)

這樣你保持模式非常簡單而有效的,因爲它不會產生較少的回溯步驟,並且,由於圖案與文字字符(右括號)結束,使得可能的位置快速搜索在正則表達式引擎「正常」行走之前模式可能成功的字符串中。

public static void Main() 
{ 
    string input = @"other[aa][][a]"; 

    string pattern = @"\[[^][]*]"; 

    Match m = Regex.Match(input, pattern, RegexOptions.RightToLeft); 

    if (m.Success) 
     Console.WriteLine("Found '{0}' at position {1}.", m.Value, m.Index); 
} 
相關問題