1

我刚刚用 C# 编写了我的程序,但我想用 Java 重写它。我想创建 spintax 文本。

我的 C# 代码:

        static string spintax(Random rnd, string str)
    {

            // Loop over string until all patterns exhausted.
            string pattern = "{[^{}]*}";
            Match m = Regex.Match(str, pattern);
            while (m.Success)
            {
                // Get random choice and replace pattern match.
                string seg = str.Substring(m.Index + 1, m.Length - 2);
                string[] choices = seg.Split('|');
                str = str.Substring(0, m.Index) + choices[rnd.Next(choices.Length)] + str.Substring(m.Index + m.Length);
                m = Regex.Match(str, pattern);
            }

            // Return the modified string.
            return str;

    }

我已将我的代码更新为

static String Spintax(Random rnd,String str)
{
    String pat = "\\{[^{}]*\\}";
    Pattern ma; 
    ma = Pattern.compile(pat);
    Matcher mat = ma.matcher(str);
    while(mat.find())
    {
        String segono = str.substring(mat.start() + 1,mat.end() - 1);
        String[] choies = segono.split("\\|",-1);
        str = str.substring(0, mat.start()) + choies[rnd.nextInt(choies.length)].toString() + str.substring(mat.start()+mat.group().length());
        mat = ma.matcher(str);
    }
    return str;
}

像魅力一样工作:D感谢大家的支持..

4

1 回答 1

1

你需要转义括号

 String pat = "\\{[^{}]*\\}";
于 2014-03-13T12:22:13.960 回答