gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:41:11 26 4
gpt4 key购买 nike

我有一个大字符串,其中可以多次出现特定单词(文本后跟一个冒号,如“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:。但是,我不知道如何快速完成上述操作。有什么想法吗?

最佳答案

Regex 非常适合这项工作 - 使用匹配评估器替换:

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

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);

关于c# - 查找特定格式的字符串在给定文本中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8630235/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com