[英]Regular expression illegal character in Java
经过很长时间的头痛之后,我一直在互联网上浏览,无法找到为什么这个正则表达式是错误的:
"\"\w*&&[\p{Punct}]\"["+sepChar+"]\"\w*&&[\p{Punct}]\""
我正在尝试使用以下模式(包括引号)读取主数据文件:
"TEXTVALUE":"TEXTVALUE":"TEXTVALUE"
并使用上述正则表达式拆分每一行。
因此,例如:
"Hello:John":"Hello:World":"Hello:Mark"
将分为:
{"Hello:John", "Hello:World", "Hello:Mark"}
反斜杠是Java中的转义字符。 您需要使用两个反斜杠\\\\
在正则表达式中包含一个反斜杠。
尝试:
"\"\\w*&&[\\p{Punct}]\"["+sepChar+"]\"\\w*&&[\\p{Punct}]\""
好。
感谢@ kevin-bowersox的帮助。
Oracle似乎在用版本7改进Java方面做得很出色。使用以下代码:
File file = new File(someFile);
BufferedReader br = new BufferedReader(file);
String line = null;
while((line = br.readLine()) != null){
//todo
}
如果文件已使用常量模式进行了格式化,例如:
"TEXTVALUE":"TEXTVALUE":"TEXTVALUE"
内容为:
"TEXTVALUE-->TEXTVALUE-->TEXTVALUE"
其中“->”代表制表符('\\ t')
因此,最后,我的解决方案是:
public ArrayList getSplittedTextFromFile(String filePath) throws FileNotFoundException, IOException{
ArrayList<String[]> ret = null;
if (!filePath.isEmpty()){
File input = new File(filePath);
BufferedReader br = new BufferedReader(input);
String line = null;
while((line = br.readLine()) != null){
String[] aSplit = line.split("\\t");
if (ret == null)
ret = new ArrayList<>();
ret.add(aSplit);
}//while
}//fi
}//fnc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.