在 Java 中根据 * 分割字符串?
我想使用 split
方法在 *
上拆分 Java 中的 String
。这是代码:
String str = "abc*def";
String temp[] = str.split("*");
System.out.println(temp[0]);
但是这个程序给了我以下错误:
Exception in thread "main" java.util.regex.PatternSyntaxException:
Dangling meta character '*' near index 0 *
我稍微调整了代码,使用 '\\*'
作为分隔符,效果很好。谁能解释这种行为(或建议替代解决方案)?
我不想使用StringTokenizer
。
I want to split a String
in Java on *
using the split
method. Here is the code:
String str = "abc*def";
String temp[] = str.split("*");
System.out.println(temp[0]);
But this program gives me the following error:
Exception in thread "main" java.util.regex.PatternSyntaxException:
Dangling meta character '*' near index 0 *
I tweaked the code a little bit, using '\\*'
as the delimiter, which works perfectly. Can anyone explain this behavior (or suggest an alternate solution)?
I don't want to use StringTokenizer
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
split()< /code>
方法实际上接受正则表达式。
*
字符在正则表达式中具有特殊含义,不能单独出现。为了告诉正则表达式使用实际的*
字符,您需要使用\
字符对其进行转义。因此,您的代码将变为:
注意
\\
:对于 Java,您还需要转义斜杠。如果您希望将来避免出现此问题,请阅读正则表达式,这样您就可以很好地了解可以使用哪些类型的表达式以及需要转义哪些字符。
The
split()
method actually accepts a regular expression. The*
character has special meaning within a regular expression, and cannot appear on its own. In order to tell the regular expression to use the actual*
character, you need to escape it with the\
character.Thus, your code becomes:
Note the
\\
: you need to escape the slash for Java as well.If you want to avoid this issue in the future, please read up on regular expressions, so you'll have a good idea of both what types of expressions you can use, as well as which characters you'll need to escape.
字符串.split() 需要一个正则表达式。在正则表达式中,
*
具有特殊含义(其前面的 0 个或多个字符类),因此必须对其进行转义。\*
完成了它。由于您使用的是 Java 字符串\\
是\
的转义序列,因此您的正则表达式将变为\*
,其行为正确。String.split() expects a regular expression. In a regular expression
*
has a special meaning (0 or more of the character class before it) so it has to be escaped.\*
accomplishes it. Since you are using a Java string\\
is the escape sequence for\
so your regular expression just becomes\*
which behaves correctly.Split 接受要分割的正则表达式,而不是字符串。正则表达式将 * 作为保留字符,因此需要使用反斜杠对其进行转义。
特别是在java中,字符串中的反斜杠也是特殊字符。它们用于换行符 (\n)、制表符 (\t) 和许多其他不太常见的字符。
因此,因为您正在编写 java,并且正在编写正则表达式,所以您需要对 * 字符进行两次转义。因此'\*'。
Split accepts a regular expression to split on, not a string. Regular expressions have * as a reserved character, so you need to escape it with a backslash.
In java specifically, backslashes in strings are also special characters. They are used for newlines (\n), tabs (\t), and many other less common characters.
So because you are writing java, and writing a regex, you need to escape the * character twice. And thus '\*'.