查找给定文本中出现特定格式的字符串的出现次数

本文关键字:字符串 格式 定格 查找 文本 | 更新日期: 2023-09-27 18:18:42

我有一个大字符串,其中可以有多个特定的单词(文本后跟一个冒号,如"test:"(。例如,像这样:

word:
TEST:
word:
TEST:
TEST: // random text
">

word"出现两次,"TEST"出现三次,但数量可以是可变的。此外,这些单词不必具有相同的顺序,并且与单词在同一行中可以有更多文本(如"TEST"的最后一个示例所示(。我需要做的是将出现次数附加到每个单词,例如输出字符串需要是这样的:

word_ONE:
TEST_ONE:
word_TWO:
TEST_TWO:
TEST_THREE: // random text

用于获取我写的这些单词的正则表达式是^'b[A-Za-z0-9_]{4,}'b:。但是,我不知道如何快速完成上述工作。有什么想法吗?

查找给定文本中出现特定格式的字符串的出现次数

正则表达式非常适合这项工作 - 使用匹配评估器替换:

此示例未经过测试或编译:

public class Fix
{
    public static String Execute(string largeText)
    {
        return Regex.Replace(largeText, "^('w{4,}):", new Fix().Evaluator);
    }
    private Dictionary<String, int> counters = new Dictionary<String, int>();
    private static String[] numbers = {"ONE", "TWO", "THREE",...};
    public String Evaluator(Match m)
    {
        String word = m.Groups[1].Value;
        int count;
        if (!counters.TryGetValue(word, out count))
          count = 0;
        count++;
        counters[word] = count;
        return word + "_" + numbers[count-1] + ":";
    }
}

这应该返回您在调用时请求的内容:

result = Fix.Execute(largeText);

我认为你可以用Regax.Replace(string,string,MatchEvaluator(和字典来做到这一点。

Dictionary<string, int> wordCount=new Dictionary<string,int>();
string AppendIndex(Match m)
{
   string matchedString = m.ToString();
   if(wordCount.Contains(matchedString))
     wordCount[matchedString]=wordCount[matchedString]+1;
   else
     wordCount.Add(matchedString, 1);
  return matchedString + "_"+ wordCount.ToString();// in the format: word_1, word_2
}

string inputText = "....";
string regexText = @"";
   static void Main() 
   {
      string text = "....";
      string result = Regex.Replace(text, @"^'b[A-Za-z0-9_]{4,}'b:",
         new MatchEvaluator(AppendIndex));
   }

看到这个:http://msdn.microsoft.com/en-US/library/cft8645c(v=VS.80(.aspx

如果我理解正确,这里不需要正则表达式。

您可以按':'字符拆分大字符串。也许您还需要逐行阅读(按''n'分割(。之后,您只需创建一个字典(IDictionary<string, int>(,用于计算某些单词的出现次数。每次找到单词 x 时,都会增加字典中的计数器。

编辑

  1. 逐行读取文件或按''n'拆分字符串

  2. 检查您的分隔符是否存在。通过按':'拆分或使用正则表达式。

  3. 从拆分数组中获取第一项或正则表达式的第一个匹配项。

  4. 使用字典来计算您的出现次数。


    if (dictionary.Contains(key)) dictionary[key]++; else dictionary.Add(key, 1);

  5. 如果您需要单词而不是数字,请为这些词典创建另一个词典。因此,如果键等于1,则dictionary[key]等于one。马拜还有另一种解决方案。

看看这个例子(我知道它不完美,也不是很好(让我们留下 Split 函数的确切参数,我认为它会有所帮助

static void Main(string[] args)
{
  string a = "word:word:test:-1+234=567:test:test:";
  string[] tks = a.Split(':');
  Regex re = new Regex(@"^'b[A-Za-z0-9_]{4,}'b");
  var res = from x in tks
  where re.Matches(x).Count > 0
  select x + DecodeNO(tks.Count(y=>y.Equals(x)));
  foreach (var item in res)
  {
    Console.WriteLine(item);
  }
  Console.ReadLine();
}
private static string DecodeNO(int n)
{
 switch (n)
 {
   case 1:
     return "_one";
   case 2:
     return "_two";
   case 3:
     return "_three";
  }
 return "";
}