开发者

Using the asterisk-character as a Java Scanner Delimiter

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 us开发者_运维知识库es 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


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.


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


Another alternative is:

Scanner in = ...;
in.useDelimiter("[*]");

Everything within the brackets are the characters you want to use as delimiters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜