Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String split question using "*"

Tags:

java

string

regex

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.

like image 251
OHHAI Avatar asked Aug 20 '09 18:08

OHHAI


People also ask

How do you split a string with a question mark in Python?

Use the re. split() method to split a string on punctuation marks, e.g. my_list = re. split('[,.!?]

How do you split a split string?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you split a string into words?

The split() method of the String class accepts a String value representing the delimiter and splits into an array of tokens (words), treating the string between the occurrence of two delimiters as one token. For example, if you pass single space “ ” as a delimiter to this method and try to split a String.

Can we split string using regex?

split(String regex) method splits this string around matches of the given regular expression. This method works in the same way as invoking the method i.e split(String regex, int limit) with the given expression and a limit argument of zero. Therefore, trailing empty strings are not included in the resulting array.


2 Answers

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

like image 117
João Silva Avatar answered Sep 21 '22 13:09

João Silva


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

like image 20
akf Avatar answered Sep 19 '22 13:09

akf