标记错误:java.util.regex.PatternSyntaxException,悬空元字符'*' [英] Tokenizing Error: java.util.regex.PatternSyntaxException, dangling metacharacter '*'
问题描述
我使用 split()
以这种格式标记用 *
分隔的字符串:
I am using split()
to tokenize a String separated with *
following this format:
name*lastName*ID*school*age
%
name*lastName*ID*school*age
%
name*lastName*ID*school*age
我正在读这个使用此代码命名为entrada.al的文件:
I'm reading this from a file named "entrada.al" using this code:
static void leer() {
try {
String ruta="entrada.al";
File myFile = new File (ruta);
FileReader fileReader = new FileReader(myFile);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
while ((line=reader.readLine())!=null){
if (!(line.equals("%"))){
String [] separado = line.split("*"); //SPLIT CALL
names.add(separado[0]);
lastNames.add(separado[1]);
ids.add(separado[2]);
ages.add(separado[3]);
}
}
reader.close();
}
我得到了这个例外:
线程main中的异常java.util.regex.PatternSyntaxException:在索引0附近悬挂元字符'*'
*
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0 *
我的猜测是原始文本文件在年龄之后缺少 *
导致此问题。我如何解决这个问题?
My guess is that the lack of a *
after age on the original text file is causing this. How do I get around it?
推荐答案
不,问题在于 *
是正则表达式中的保留字符,因此您需要将其转义。
No, the problem is that *
is a reserved character in regexes, so you need to escape it.
String [] separado = line.split("\\*");
*
表示零或更多上一个表达(参见 模式
Javadocs ),你没有给它任何先前的表达,使你的拆分表达非法。这就是错误是 PatternSyntaxException
。
*
means "zero or more of the previous expression" (see the Pattern
Javadocs), and you weren't giving it any previous expression, making your split expression illegal. This is why the error was a PatternSyntaxException
.
这篇关于标记错误:java.util.regex.PatternSyntaxException,悬空元字符'*'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!