2017-04-24 67 views
3

編輯的所有比賽: 我有一個string str = "where dog is and cats are and bird is bigger than a mouse"並希望whereandandandand和句子的末尾之間的提取分離子。結果應該是:dog is,cats are,bird is bigger than a mouse。 (樣本字符串可能包含whereand ECT之間的任何字符串。)正則表達式沒有找到

List<string> list = new List<string>(); 
string sample = "where dog is and cats are and bird is bigger than a mouse"; 
MatchCollection matches = Regex.Matches(sample, @"where|and\s(?<gr>.+)and|$"); 
foreach (Match m in matches) 
    { 
    list.Add(m.Groups["gr"].Value.ToString()); 
    } 

但它不工作。我知道正則表達式是不正確的,所以請幫我解決這個問題。謝謝。

+3

究竟是什麼你想要做什麼?拆分'where'和'and'或者匹配'dog is','cat is'和'bird is'?你在尋找什麼樣的模式? – Rahul

+0

@Rahul我試圖提取'where'和'and',或'and'和'和'之間的任何子字符串。 '狗是'和其他只是例子。 –

+0

發佈一些更多的例子會更好。 – Rahul

回答

2

使用大括號修復|和回顧後:

using System; 
using System.Text.RegularExpressions; 

public class Solution 
{ 
    public static void Main(String[] args) 
    { 
     string sample = "where dog is and cats are and bird is bigger than a mouse"; 
     MatchCollection matches = Regex.Matches(sample, @"(?<=(where|and)\s)(?<gr>.+?)(?=(and|$))"); 
     foreach (Match m in matches) 
     { 
      Console.WriteLine(m.Value.ToString()); 
     } 
    } 
} 

小提琴:https://dotnetfiddle.net/7Ksm2G

輸出:

dog is 
cats are 
bird is bigger than a mouse 
+0

謝謝!我會嘗試一下 –

3

如何"\w+ is"

List<string> list = new List<string>(); 
string sample = "where dog is and cat is and bird is"; 
MatchCollection matches = Regex.Matches(sample, @"\w+ is"); 
foreach (Match m in matches) 
{ 
    list.Add(m.Value.ToString()); 
} 

樣品:https://dotnetfiddle.net/pMMMrU

+1

謝謝,但是如果我想提取'where'和'and',或'and'和'和'之間的任何子字符串。不僅'狗'可以在那個地方。 –

1

您應該使用Regex.Split()方法不Regex.Match()

string input = "where dog is and cats are and bird is bigger than a mouse"; 
    string pattern = "(?:where|and)"; 
    string[] substrings = Regex.Split(input, pattern); 
    foreach (string match in substrings) 
    { 
     Console.WriteLine("'{0}'", match); 
    } 

這將分裂的文字的話whereand

Ideone Demo

+0

雖然這是一個可行的解決方案,但OP需要提供更多詳細信息。如果前面的空格是有效的?或更復雜的句子。 – Rahul

+1

謝謝。它幾乎可以工作。它匹配'where'之前的字母以及 –