Edited:
I have a string str = "where dog is and cats are and bird is bigger than a mouse" and want to extract separate substrings between where and and, andand and, and and the end of the sentence. The result should be: dog is, cats are, bird is bigger than a mouse. (Sample string may contain any substrings between where and and 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());
}
But it doesn't work. I know that regular expression is not right, so please help me to correct that. Thanks.
How about "\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());
}
Sample: https://dotnetfiddle.net/pMMMrU
Using braces to fix the | and a lookbehind:
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());
}
}
}
Fiddle: https://dotnetfiddle.net/7Ksm2G
Output:
dog is
cats are
bird is bigger than a mouse
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With