javaspintax

Java - Spintax , what should i do?


I just wrote my program in C# but I want rewrite it in Java. I want create spintax text.

My C# code:

        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;

    }

I've Updated My Code to

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

works like a charm :D thanks all for your support..


Solution

  • You need to escape the brackets

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