编辑:
我有一个string str = "where dog is and cats are and bird is bigger than a mouse"
,想要在where
和and
,and
和and
,and
和句子结尾之间提取单独的子字符串。结果应为:dog is
,cats are
,bird is bigger than a mouse
。 (示例字符串可能包含where
和and
之间的任何子字符串。)
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());
}
但它不起作用。我知道正则表达不对,所以请帮我纠正。感谢。
答案 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());
}
答案 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 强>