如何使用Regex在String中查找Char的前x次出现

时间:2011-08-19 11:14:22

标签: c# regex

我试图找出如何在字符串中获取字符串的第一个x匹配。我尝试使用Matchcollection,但在x'd-match之后我无法找到任何后退序列。

供参考: 我需要这个字符串,它具有可变长度和搜索字符的不同出现次数,因此只需获取所有并且仅使用第一个x不是解决方案。

提前致谢

编辑: 我正在使用Steam阅读器从.txt文件中获取信息并将其写入atring,每个文件一个字符串。这些atrings长度非常不同。在每个字符串中都可以说3个关键字。但有时出现问题,我只有一两个关键字。关键字之间是用;分隔的其他字段。因此,如果我使用Matchcollection来获取;的索引,并且缺少一个关键字,则会移动文件中的信息。因此,我需要在(现有)关键字之前/之后找到第一个x occourencces。

4 个答案:

答案 0 :(得分:1)

你真的想使用Regex,这样的事情不会吗?

string simpletext = "Hello World";
int firstoccur = simpletext.IndexOfAny(new char[]{'o'});

由于您想要该角色的所有索引,您可以尝试这种方式

string simpletext = "Hello World";
int[] occurences = Enumerable.Range(0, simpletext.Length).Where(x => simpletext[x] == 'o').ToArray();

答案 1 :(得分:0)

您可以使用课程Match。这个类只返回一个结果,但你可以遍历字符串直到它找到最后一个结果。

这样的事情:

Match match = Regex.Match(input, pattern);
int count = 0;

while (match.Success)
{
    count++;

    // do something with match

    match = match.NextMatch();

    // Exit the loop when your match number is reached
}

答案 2 :(得分:0)

如果您决定使用正则表达式,那么我会使用匹配而不是实际匹配来执行此操作;主要是因为你预先计算了数量。

string pattern = "a";
string source = "this is a test of a regex match";
int maxMatches = 2;

MatchCollection mc = Regex.Matches(source, pattern);

if (mc.Count() > 0)
{
  for (int i = 0; i < maxMatches; i++) 
  {
    //do something with mc[i].Index, mc[i].Length
  }
}

答案 3 :(得分:0)

拆分操作非常快,因此如果不需要正则表达式,可以使用它:

public static IEnumerable<int> IndicesOf(this string text, char value, int count)
        {
            var tokens = text.Split(value);
            var sum = tokens[0].Length;
            var currentCount = 0;
            for (int i = 1; i < tokens.Length && 
                            sum < text.Length && 
                            currentCount < count; i++)
            {
                yield return sum;
                sum += 1 + tokens[i].Length;
                currentCount++;
            }
        }

在正则表达式的大约60%的时间内执行