2011-07-31 29 views
0

我需要找到一個句子中的詞彙和一些像這樣:需要C#RegEx來查找單詞和數字。

狀態Mchine是在第4階段。下一階段排隊。

我需要找到只有狀態和數字4,並忽略其餘。

我有這樣的:

@"\b(state)(?:\W+\w+){1,10}?\W+(\d)*\b" 

,但它也包括在比賽之間的所有的話。

我在做什麼錯?

+0

我們展示你的代碼。我大概可以猜到你得到了匹配數組的第一個元素,其中包括整個匹配,而不是匹配在括號內的匹配。 –

+0

這裏是來自thre代碼的snip,它試圖檢測隊列的狀態,並且需要查找短語「狀態」和某些時間「狀態」,並且需要檢索狀態代碼。字符串line1;字符串errcode = @「\ b(status | error | state)\ b(?:\ W + \ w +){1,10}?\ W + \ b(\ d)* \ b」;正則表達式defaultRegex = new Regex(errcode,RegexOptions.IgnoreCase); MatchCollection myMatchCollection = Regex.Matches(line1,errcode); richTextBox1.AppendText(myMatchCollection.Count.ToString()); (myMatch.ToString()); – SamRam

+0

我不確定你想從文本中捕獲什麼。你需要這個號碼,還有什麼? –

回答

0

試試這個:

var input = "The state Mchine is at stage 4. next stage is queued."; 
      var pattern = @"[^\s]+.(?<state>\w+)[\w\s]+(?<stage>\d+)\."; 
      var match = Regex.Match(input, pattern, RegexOptions.IgnoreCase); 
      Console.WriteLine(match.Groups["state"].Value); //state 
      Console.WriteLine(match.Groups["stage"].Value); //4 
      Console.ReadLine(); 
+0

謝謝,工作很好,但是當我讀這條線它回來空白和沒有匹配? 「你的工作人員在處理狀態490時卡住了。」 我將模式更改爲@「[^ \ s] +。\ b(? \ w +)\ b [\ w \ s] +(?(\ d)*)\」。 但是,這仍然沒有奏效。任何建議將不勝感激 – SamRam

+0

這是從三線代碼,試圖檢測隊列的狀態,需要尋找短語「狀態」和有時「狀態」,將需要檢索狀態代碼片段。 string line1; string errcode = @「\ b(status | error | state)\ b(?:\ W + \ w +){1,10}?\ W + \ b(\ d)* \ b」;正則表達式defaultRegex = new Regex(errcode,RegexOptions.IgnoreCase); MatchCollection myMatchCollection = Regex.Matches(line1,errcode); richTextBox1.AppendText(myMatchCollection.Count.ToString()); foreach(在myMatchCollection中匹配myMatch) { richTextBox1.AppendText(myMatch.ToString()); } – SamRam

+0

@SamRam如果問題沒有解決,請不要點擊答案下的綠色檢查。等到您的問題得到解答後,您可以點擊相應答案上的複選標記。 –