2012-12-20 46 views
5

假設有其象下面這樣的文字:獲取文本的特定部分在嚴格的文本

string str = @"stackoverflow(:stackoverflow)overstackflow(超過:stackoverflow)";

我想大膽領域。 我想我必須要找到「(」和「:」文本,並讓他們之間的文字是不是

任何意見

+0

你的意思是在你的字符串中間的反引號?目前他們正在對您的代碼進行解碼。 – Rawling

+0

假設有一個文本,我想得到的文本beween(和:操作符。我該怎麼做? –

+0

你想得到是/否的答案?爲什麼不自己嘗試? – slawekwin

回答

6

也許與普通string方法:

IList<String> foundStrings = new List<String>(); 
int currentIndex = 0; 
int index = str.IndexOf("(", currentIndex); 
while(index != -1) 
{ 
    int start = index + "(".Length; 
    int colonIndex = str.IndexOf(":", start); 
    if (colonIndex != -1) 
    { 
     string nextFound = str.Substring(start, colonIndex - start); 
     foundStrings.Add(nextFound); 
    } 
    currentIndex = start; 
    index = str.IndexOf("(", currentIndex); 
} 

Demo

+0

謝謝Tim Schmelter,這真的很酷.. –

+0

@Tim當你在SO中回答或者使用Visual Studio時,你只使用[ideone.com](http://ideone.com)嗎?是ideone更快? –

+0

@SonerGönül:僅用於演示目的,不是更快,它使用單聲道有很多限制 –

1
string strRegex = @"\((.+?)\:"; 
RegexOptions myRegexOptions = RegexOptions.None; 
Regex myRegex = new Regex(strRegex, myRegexOptions); 
string strTargetString = @"stackoverflow(stack:stackoverflow)overstackflow(over:stackoverflow)"; 

foreach (Match myMatch in myRegex.Matches(strTargetString)) 
{ 
    if (myMatch.Success) 
    { 
    // Add your code here 
    } 
} 
+0

檢查'myMatch.Success'沒有意義,但你可能想要展示如何獲得'Value 'out。 – Rawling

1

我會去這樣的事情:

Regex matcher = new Regex(@"([^():}]+)\(([^():}]*):([^():}]*)\)"); 
MatchCollection matches = matcher.Matches(str); 

這會去翻你輸入的一切,看起來像group1(group2:group3)。 (如果任何一組包含():整個事情將被忽略,因爲它不能找出的意思是在那裏。)

然後,您可以得到匹配的值作爲例如

foreach(Match m in matches) 
{ 
    Console.WriteLine("First: {0}, Second: {1}, Third{2}", 
     m.Groups[1].Value, m.Groups[2].Value, m.Groups[3].Value); 
} 

所以如果你只是想(:之間的位可以使用

foreach(Match m in matches) 
{ 
    Console.WriteLine(m.Groups[2].Value); 
} 
1
public static void Main(string[] args) 
     { 
      string str = @"stackoverflow(stack:stackoverflow)overstackflow(over:stackoverflow)"; 
      Console.WriteLine(ExtractString(str)); 
     } 

     static string ExtractString(string s) 
     { 
      var start = "("; 
      int startIndex = s.IndexOf(start) + start.Length; 
      int endIndex = s.IndexOf(":", startIndex); 
      return s.Substring(startIndex, endIndex - startIndex); 
     } 

結果是stack,但是您可以在循環中使用它以循環迭代到字符串。

Demo