15

Let's say have a string...

String myString =  "my*big*string*needs*parsing";

All I want is to get an split the string into "my" , "big" , "string", etc. So I try

myString.split("*");

returns java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0

* is a special character in regex so I try escaping....

myString.split("\\*");

same exception. I figured someone would know a quick solution. Thanks.

OHHAI
  • 7,845
  • 5
  • 19
  • 9
  • your right \\* does work, I was using it from an array... myArray[x].split("\\*"); and it was throwing an exception but if I if turn myArray[x] into a string first and then run it it works... thanks for the answers :) – OHHAI Aug 20 '09 at 19:03
  • i mean double \ in the above comment.... – OHHAI Aug 20 '09 at 19:04

6 Answers6

23

split("\\*") works with me.

João Silva
  • 89,303
  • 29
  • 152
  • 158
5

One escape \ will not do the trick in Java 6 on Mac OSX, as \ is reserved for \b \t \n \f \r \'\" and \\. What you have seems to work for me:

public static void main(String[] args) {
    String myString =  "my*big*string*needs*parsing";
    String[] a = myString.split("\\*");
    for (String b : a) {
        System.out.println(b);
    }
}

outputs:

my
big
string
needs
parsing

akf
  • 38,619
  • 8
  • 86
  • 96
1

http://arunma.com/2007/08/23/javautilregexpatternsyntaxexception-dangling-meta-character-near-index-0/

Should do exactly what you need.

Dirk
  • 6,774
  • 14
  • 51
  • 73
0

This happens because the split method takes a regular expression, not a plain string.

The '*' character means match the previous character zero or more times, thus it is not valid to specify it on its own.

So it should be escaped, like following

split("\\*")

Pavithra Gunasekara
  • 3,902
  • 8
  • 36
  • 46
0

myString.split("\\*"); is working fine on Java 5. Which JRE do you use.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
jatanp
  • 3,982
  • 4
  • 40
  • 46
0

You can also use a StringTokenizer.

 StringTokenizer st = new StringTokenizer("my*big*string*needs*parsing", "\*");
 while (st.hasMoreTokens()) {
     System.out.println(st.nextToken());
 }
Milhous
  • 14,473
  • 16
  • 63
  • 82