简体   繁体   中英

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..

你需要逃脱括号

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM