C#正则表达式匹配候选词
来自文心一言(多次修改才正确的):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | public App() { string input = "例子文字{备选,:'词1t324|备选词2gdfg,该方法|备选词3dsfdsf}继续{备选..*&fdgfd54词A|备选词.*&fdgfd54B|备选词.*&fdgfd54C}话术内容" ; string result = ReplaceAlternatives(input); Console.WriteLine(result); } static string ReplaceAlternatives( string input) { string pattern = @"\{([^}]+)\}" ; MatchCollection matches = Regex.Matches(input, pattern); Random random = new Random(); StringBuilder sb = new StringBuilder(input); int offset = 0; // 用于跟踪已经进行的替换导致的索引偏移 foreach (Match match in matches) { // 由于之前的替换,我们需要调整当前匹配项的索引 int adjustedIndex = match.Index - offset; string alternatives = match.Groups[1].Value; string [] options = alternatives.Split( '|' ); int randomIndex = random.Next(options.Length); string chosenOption = options[randomIndex]; // 计算要移除的字符串长度(即匹配项的长度) int removeLength = match.Length; // 执行替换 sb.Remove(adjustedIndex, removeLength); sb.Insert(adjustedIndex, chosenOption); // 更新偏移量 offset += removeLength - chosenOption.Length; } return sb.ToString(); } } |
fffffffffffffffff
test red font.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 字符编码:从基础到乱码解决