Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression doesn't find all the matches

Tags:

string

c#

regex

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.

like image 843
Denis Lolik Avatar asked Dec 29 '25 05:12

Denis Lolik


2 Answers

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

like image 88
fubo Avatar answered Dec 30 '25 21:12

fubo


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
like image 45
Yunnosch Avatar answered Dec 30 '25 22:12

Yunnosch