String split question using “*”

前端 未结 6 1791
梦毁少年i
梦毁少年i 2021-01-04 02:36

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\" , \"bi

相关标签:
6条回答
  • 2021-01-04 02:55

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

    Should do exactly what you need.

    0 讨论(0)
  • 2021-01-04 03:01

    You can also use a StringTokenizer.

     StringTokenizer st = new StringTokenizer("my*big*string*needs*parsing", "\*");
     while (st.hasMoreTokens()) {
         System.out.println(st.nextToken());
     }
    
    0 讨论(0)
  • 2021-01-04 03:02

    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

    0 讨论(0)
  • split("\\*") works with me.

    0 讨论(0)
  • 2021-01-04 03:10

    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("\\*")

    0 讨论(0)
  • 2021-01-04 03:14

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

    0 讨论(0)
提交回复
热议问题