正则表达式找不到所有匹配项

时间:2017-04-24 14:17:25

标签: c# regex string

编辑: 我有一个string str = "where dog is and cats are and bird is bigger than a mouse",想要在whereandandandand和句子结尾之间提取单独的子字符串。结果应为:dog iscats arebird is bigger than a mouse。 (示例字符串可能包含whereand之间的任何子字符串。)

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 个答案:

答案 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 :(得分: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

答案 2 :(得分:1)

您应该使用MyClass方法而不是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); } where

<强> Ideone Demo

相关问题