Java - Spintax,我该怎么办?

时间:2014-03-13 12:17:46

标签: java spintax

我刚用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;
}

就像一个魅力:感谢所有人的支持..

1 个答案:

答案 0 :(得分:1)

您需要转义括号

 String pat = "\\{[^{}]*\\}";