Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

Tokenizing Error: java.util.regex.PatternSyntaxException, dangling metacharacter '*'

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

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();
    }

And I'm getting this exception:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, the problem is that * is a reserved character in regexes, so you need to escape it.

String [] separado = line.split("\*");

* 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...