为什么我用调用findInLine的时候,直接写sc.findInLine("\\w+): (\\w+)\\((\\w+)")就没问题,但是我把参数保存成一个String类型的变量传递进去就出错?如下:sc.findInLine(pattern);pattern是String类型的,内容跟上述直接写的一样,抛出异常 java.util.regex.PatternSyntaxException: Unclosed group near index 23 (\\w+): (\\w+)\\((\\w+)
解决方案 »
- <xsd:element saw-name:hello="world"/>如何解析?
- 求Thinking in java第三版课后习题答案.谢谢.
- ApplicationWindow createContents() Question ,Thanks for ur suggestion.......vexation--vexation
- 请问怎么用JAVA来做一个网络上的下载工具
- 求助:这样用递归式为什么出错?
- 关于JTree的用法?
- struts的logic:iterate问题,困惑了好几天
- How can I include JVM instructions in my Java Program to increase the efficiency of my code.
- String temp = System.getProperty("pmIndex")的问题 求指点
- JNI 改变String参数的值! 急急急!!!
- 从JTextField向数据库中插入数据
- 用sql 和vb开发程序出现"错误3704,对象关闭时对象不允许操作"
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+)"
将文件in.file中的
"(\\w+): (\\w+)\\((\\w+)" 改为
"(\w+): (\w+)\((\w+)"
你的正则表达式的内容应该是 (\w+): (\w+)\((\w+)
写成字符串要将 \ 写成转义字符形式 \\