C#:在字符串中查找字符串的实例 [英] C#: finding instances of a string within a string
问题描述
假如我有字符串1,2和3或4,并希望创建一个字符串数组,其中包含所有子AND或OR,依次字符串中找到。
Suppose I had the string "1 AND 2 AND 3 OR 4", and want to create an array of strings that contains all substrings "AND" or "OR", in order, found within the string.
所以上面的字符串将返回一个字符串数组{和,和,或}
So the above string would return a string array of {"AND", "AND", "OR"}.
?什么是书面的一个聪明的办法
What would be a smart way of writing that?
编辑:
使用C#2.0 +
Using C# 2.0+,
string rule = "1 AND 2 AND 3 OR 4";
string pattern = "(AND|OR)";
string[] conditions = Regex.Split(rule, pattern);
给我{1,和,2,和,3 ,或,4},这是不太我后。我怎样才能降低到AND和OR只?
gives me {"1", "AND", "2", "AND", "3", "OR", "4"}, which isn't quite what I'm after. How can I reduce that to the ANDs and ORs only?
推荐答案
这正则表达式(.NET),似乎做你想要什么。您正在寻找在指数= 1组中的比赛(多):
This regex (.NET) seems to do what you want. You're looking for the matches (multiple) in the group at index=1:
.*?((AND)|(OR))*.*?
修改我测试过以下,似乎做什么你想。它更多的行比我想的,但它在一个纯粹的正则表达式的方式接近的任务(这恕我直言,是你应该做的事情):
EDIT I've tested the following and it seems to do what you want. It's more lines than i would like but it approaches the task in a purely regex fashion (which IMHO is what you should be doing):
string text = "1 AND 2 AND 3 OR 4";
string pattern = @"AND|OR";
Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
Match m = r.Match(text);
ArrayList results = new ArrayList();
while (m.Success)
{
results.Add(m.Groups[0].Value);
m = m.NextMatch();
}
string[] matchesStringArray = (string[])results.ToArray(typeof(string));
这篇关于C#:在字符串中查找字符串的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!