问题
Hey Everyone, This question seems really silly to me, but I can't for the life of me find the answer anywhere. All I'm trying to do, is scan a string that is delimited with an asterisk (* ). However, when I try foo.useDelimiter("*");, Java interprets the asterisk as a wildcard, and uses EVERY character as a delimiter... This is obviously not what I want. I've tried using a backslash as an escape character, but that gives me the compiler error "illegal escape character".
This is probably very simple, but once again, I have no idea where to find the answer!
Thanks a lot!
Linus
回答1:
In a Java string, you want to use a double backslash \\ so the actual string that will be interpreted is \*, thus escaping the *.
Essentially, you have to escape the escape character.
回答2:
Since Scanner uses the same Pattern class as other regexp operations, two backslashes should do the trick.
(One backslash only escapes the next character in the string constant, you need two of them to get one in the actual string.)
回答3:
Another alternative is:
Scanner in = ...;
in.useDelimiter("[*]");
Everything within the brackets are the characters you want to use as delimiters.
来源:https://stackoverflow.com/questions/4683938/using-the-asterisk-character-as-a-java-scanner-delimiter