2014-01-16 40 views
0

我需要解決我的問題。我有一個條款,如:字符串中的子字符串或分詞

你好,大家好我酷(測試)

的,現在我需要一個有效的方法來僅僅只有部分在括號分割,其結果應該是:

測試

我的嘗試是分割等單詞中的字符串。但我不認爲這是最好的方式。

string[] words = s.Split(' '); 
+0

當你說鉗我認爲你的意思是括號? – Liath

回答

4

我不認爲拆分是解決你的問題

正則表達式是用於提取數據非常好。

using System.Text.RegularExpression; 
... 
string result = Regex.Match(s, @"\((.*?)\)").Groups[1].Value; 

這應該是關鍵。

0

您可以使用正則表達式是:

string parenthesized = Regex.Match(s, @"(?<=\()[^)]+(?=\))").Value; 

這裏的正則表達式的各個部分的解釋:

  • (?<=\():回顧後的((從匹配排除)
  • [^)]+:由除之外的任何東西組成的字符序列
  • (?=\)):前瞻的)(從比賽除外)
+0

如果我用你的正則表達式方法與我的字符串我沒有得到任何東西.... – Butters

+0

我只需要只是測試解決方案字符串 – Butters

+0

@Butters:我已經更新了代碼;請再次測試。 – Douglas

0

最有效的方法是使用字符串方法,但不需要Split,但SubstringIndexOf。請注意,這只是目前發現在括號中的字:

string text = "Hello guys I am cool (test)"; 
string result = "--no parentheses--"; 
int index = text.IndexOf('('); 
if(index++ >= 0) // ++ used to look behind (which is a single character 
{ 
    int endIndex = text.IndexOf(')', index); 
    if(endIndex >= 0) 
    { 
     result = text.Substring(index, endIndex - index); 
    } 
} 
+0

你真的認爲這個解決方案比簡單的正則表達式快得多嗎?你有沒有執行/看過任何基準?沒有他們,它看起來像微型優化成本的可讀性... –

+0

@KonradKokosa:OP提到_effective_和使用的字符串方法。這就是我提供'Substring'的原因。這取決於文本的大小,或者你經常使用這種方法。但即使它沒有改變,也只能知道它如何與字符串方法一起工作。 –

+0

我只是想知道在這個和正則表達式之間的效率方面會有多少次的調用會有所不同。當然,知道這個選擇是很好的。 –

1

假設:

var input = "Hello guys I am cool (test)"; 

..Non正則表達式版本:

var nonRegex = input.Substring(input.IndexOf('(') + 1, input.LastIndexOf(')') - (input.IndexOf('(') + 1)); 

..Regex版本:

var regex = Regex.Match(input, @"\((\w+)\)").Groups[1].Value; 
-2
string s = "Hello guys I am cool (test)"; 
var result = s.Substring(s.IndexOf("test"), 4); 
+2

這段代碼實際上等同於只寫'var result =「test」'。你應該假設OP想要匹配括號中的其他字符串。 – Douglas

+2

我降低了投票率。 OP的要求是在括號之間匹配_whatever_。這只是發現「測試」。 –