开发者

Splitting a String on * in Java?

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.


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:

String str = "abc*def";
String temp[] = str.split("\\*");
System.out.println(temp[0]);    // Prints "abc"

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.


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 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 '\*'.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜