弹来弹去跑马灯!

C#正则表达式匹配候选词

来自文心一言(多次修改才正确的):

    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 @ 2024-12-02 08:46  wgscd  阅读(3)  评论(0编辑  收藏  举报