线程" main"中的例外情况java.util.regex.PatternSyntaxException:非法重复

时间:2015-05-22 11:36:45

标签: java exception

public static void main(String s[]) {
        System.out.println(new Binary().meth());
            }
 String meth(){
     String source = "{Hi|Hello|Hey}, how are you {today|doing}?";
     List<String> list1=new ArrayList<String>();
     List<String> list2=new ArrayList<String>();
     String[] strg=source.split("{");
     for(String str: strg){
         String[] data=str.split("}");
         list1.add(data[0]);
         list2.add(data[1]);
     }
     Random random = new Random();
     String[] req=new String[list1.size()];
     int i=0;
     for(String str: list1){
         req[i++]= str.split("|")[random.nextInt(str.split("|").length)];
     }
     int j=0;
     String result="";
     for(String str: list2){
         result=result+req[j++]+str;
     }
     return result;
 }
}

在caharacter {的基础上拆分字符串给我跟随错误 -

Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition
{
    at java.util.regex.Pattern.error(Unknown Source)
    at java.util.regex.Pattern.closure(Unknown Source)
    at java.util.regex.Pattern.sequence(Unknown Source)
    at java.util.regex.Pattern.expr(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at java.util.regex.Pattern.<init>(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at java.lang.String.split(Unknown Source)
    at java.lang.String.split(Unknown Source)
    at Binary.meth(Binary.java:16)
    at Binary.main(Binary.java:10)

1 个答案:

答案 0 :(得分:5)

{是正则表达式中的一个特殊字符,你需要逃避它,

使用以下:

source.split("\\{");