使用星号字符作为 Java 扫描器分隔符
嘿大家, 这个问题对我来说似乎很愚蠢,但我一生都无法在任何地方找到答案。我想做的就是扫描一个用星号 (*) 分隔的字符串。然而,当我尝试 foo.useDelimiter("*"); 时,Java 将星号解释为通配符,并使用每个字符作为分隔符......这显然不是我想要的。 我尝试使用反斜杠作为转义字符,但这给了我编译器错误“非法转义字符”。
这可能很简单,但我再次不知道在哪里可以找到答案!
多谢!
莱纳斯
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Java 字符串中,您希望使用双反斜杠 \\,因此将解释的实际字符串是 \*,从而转义 *。
本质上,你必须转义转义字符。
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.
由于 Scanner 使用与其他正则表达式操作相同的 Pattern 类,因此两个反斜杠应该可以解决问题。
(一个反斜杠仅转义字符串常量中的下一个字符,您需要其中两个反斜杠才能在实际字符串中得到一个反斜杠。)
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:
Everything within the brackets are the characters you want to use as delimiters.