Using the asterisk-character as a Java Scanner Delimiter

こ雲淡風輕ζ 提交于 2019-12-02 05:55:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!