繁体   English   中英

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

[英]Regular Expression doesn't find all the matches

编辑:我有一个string str = "where dog is and cats are and bird is bigger than a mouse" ,并要提取之间的单独子whereandandandand和句子的末尾。 结果应该是: dog iscats arebird is bigger than a mouse (示例字符串可能包含where 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());
  }

但它不起作用。 我知道正则表达不对,所以请帮我纠正。 谢谢。

怎么样"\\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

使用大括号来修复| 和一个看守:

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

您应该使用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演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM