views:

205

answers:

5

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.

+1  A: 

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

JG
\\* works for me too!
Michael Wiles
A: 

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

jatanp
Single slash won't work; \* isn't a special character. I think you made a typo:)
extraneon
+1  A: 

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
A: 

You can also use a StringTokenizer.

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