2014-12-24 93 views
-4

我有一個包含以下內容的字符串:獲取文本括號內

test (alpha) 

我想,括號內的文字,這樣我只有alpha。這可以使用正則表達式來實現,例如\(([^)]*)\)。有更容易的方法嗎?

+0

string.IndexOf和string.Substring改變posLast的提取,但它需要的代碼 – Steve

+0

多行通過使用簡單的正則表達式或者'\(( ('(',')')[1]' – t3chb0t

+0

更容易,你的意思是非正則表達式的方式嗎? – imlokesh

回答

2

你的正則表達式很簡單。如果你不想創建兩個索引,如果你想實現這個沒有任何捕獲組,那麼你可以使用基於lookaround的正則表達式,如下所示。

Regex rgx = new Regex(@"(?<=\()[^()]*(?=\))"); 

DEMO

  • (?<=\()正回顧後,它斷言匹配必須由開口paranthesis (之前。

  • [()]*匹配任何字符,但不匹配()零次或多次。

  • (?=\))積極向前,它聲稱匹配後必須跟一個)關閉panthesis。

IDEONE

+2

這看起來好多了;-) – t3chb0t

+0

有一個谷歌周圍 - 不知道如何看待代碼?它使用.Regex? – JHarley1

+1

我不認爲這個看起來很容易在正則表達式的初學者... – nhahtdh

1

的非正則表達式的解決方案。

string test = "test (alpha)"; 
int posFirst = test.IndexOf("("); 
int posLast = test.LastIndexOf(")"); 
if(posFirst>= 0 && posLast >= 0) 
{ 
    string result = test.Substring(posFirst + 1, (posLast - posFirst -1)); 
    Console.WriteLine(result); 
} 

這將採取一切內部的第一個開放paren到最後一個關閉。
如果你只想要去的第一個右括號,然後使用的IndexOf