gpt4 book ai didi

c# - 自定义标签中的正则表达式替换

转载 作者:太空宇宙 更新时间:2023-11-03 20:47:49 25 4
gpt4 key购买 nike

我有一个字符串,可能包含以下一个或多个标签:

<CHOICE [some words] [other words]>

我需要替换 (C#) 所有出现的这个标签,如下所示:

Example: I like <CHOICE [cars and bikes] [apple and oranges]>
Result: I like cars and bikes
Example: I like <CHOICE [cars and bikes] [apple and oranges]>, I also like <CHOICE [pizza] [pasta]>
Result: I like cars and bikes, I also like pizza

基本上,只用第一组括号中出现的字符串替换整个标签。

看起来捕获组是可行的方法,但我无法理解如何使它们工作。

感谢任何帮助!

编辑:Regex 不是必需的,我认为这将是最好的方法,但我看到一些评论告诉我不需要它,所以任何其他建议都一样好。谢谢!

最佳答案

纯属娱乐。这是一个校园 foreach 状态机,具有线性 O(n) 时间复杂度

var line = "I like <CHOICE [cars and bikes] [apple and oranges]>";

var result = new StringBuilder();
var state = 0;

foreach (char c in line)
{
if (state == 0 && c == '<') state = 1;
else if (state == 1 && c == '[') state = 2;
else if (state == 2 && c == ']') state = 3;
else if (state == 3 && c == '>') state = 0;
else if (state == 0 || state == 2) result.Append(c);
};

输出

I like cars and bikes

Demo here

关于c# - 自定义标签中的正则表达式替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59044851/

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