Regular expression does not find all matches
Edited:
I have string str = "where dog is and cats are and bird is bigger than a mouse"
and want to extract the individual substrings between where
and and
, and
and and
, and
and the end of a sentence. The result should be: dog is
, cats are
, bird is bigger than a mouse
. (The sample string can 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 that won't work. I know the regex is wrong, so please help me fix this. Thank.
source to share
Using curly braces to fix |
and 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
source to share
What 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
source to share
You must use the Regex.Split()
not method 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);
}
It will split into literal words where
and and
.
source to share