弹来弹去跑马灯!

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

  

posted @   wgscd  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 字符编码:从基础到乱码解决
点击右上角即可分享
微信分享提示