为什么我用调用findInLine的时候,直接写sc.findInLine("\\w+): (\\w+)\\((\\w+)")就没问题,但是我把参数保存成一个String类型的变量传递进去就出错?如下:sc.findInLine(pattern);pattern是String类型的,内容跟上述直接写的一样,抛出异常 java.util.regex.PatternSyntaxException: Unclosed group near index 23 (\\w+): (\\w+)\\((\\w+)

解决方案 »

  1.   

    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Scanner;
    import java.util.regex.MatchResult;
    public class PatternTest { /**
     * @param args
     */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    String sp = "(\\w+): (\\w+)\\((\\w+)",sp1,temp;
    sp1 = new String();
    temp = new String();
    String str = "abc: def(ghi";

    try {
    BufferedReader in = new BufferedReader( new FileReader("in.file"));
    while( (temp = in.readLine()) != null )
    {
    System.out.println( temp );
    int start,end;
    start = temp.indexOf('"');
    end = temp.lastIndexOf('"'); sp1 = temp.substring(start+1,end);
    System.out.println( sp1 ); }
    } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } Scanner sc = new Scanner(str);
    // sc.findInLine("(\\w+): (\\w+)\\((\\w+)");
    sc.findInLine(sp1);
    MatchResult result = sc.match();
    for (int i=1; i<=result.groupCount(); i++)
    {
    System.out.println(result.group(i));
    }

    }
    }这是结果:
    "(\\w+): (\\w+)\\((\\w+)"
    (\\w+): (\\w+)\\((\\w+)
    Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed group near index 23
    (\\w+): (\\w+)\\((\\w+)
                           ^
    at java.util.regex.Pattern.error(Unknown Source)
    at java.util.regex.Pattern.accept(Unknown Source)
    at java.util.regex.Pattern.group0(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.util.Scanner$1.create(Unknown Source)
    at java.util.Scanner$1.create(Unknown Source)
    at sun.misc.LRUCache.forName(Unknown Source)
    at java.util.Scanner.findInLine(Unknown Source)
    at PatternTest.main(PatternTest.java:44)用注释掉的sc.findInLine("(\\w+): (\\w+)\\((\\w+)");这一句就没问题,或者把sp1改成sp也没问题,就是sc.findInLine(sp)也没问题。问题好像出在读进来的String里,但是打印出来的是一样啊。in.file文件里只有下面的一行字符
    "(\\w+): (\\w+)\\((\\w+)"
      

  2.   

    问题找到:
    将文件in.file中的
    "(\\w+): (\\w+)\\((\\w+)" 改为
    "(\w+): (\w+)\((\w+)"
      

  3.   

    原因如下:
    你的正则表达式的内容应该是 (\w+): (\w+)\((\w+)
    写成字符串要将 \ 写成转义字符形式 \\