Question

I need to split a text (String), the text is just like this:

[title],[description blablablablablabla]

Is there a way to do this? I need to store in a String[] the 2 texts between brackets, separated by a ",".

Was it helpful?

Solution 2

You can use Pattern and Matcher:

String input = "[title],[description blablablablablabla]";

Pattern pattern = Pattern.compile("\\[(.*?)\\]");
Matcher matcher = pattern.matcher(input);
ArrayList<String> stringList = new ArrayList<String>();

while(matcher.find()) {
    stringList.add(matcher.group(1));
}

//If you just need the results to be stored in an array of Strings anyway.
String[] stringArray = stringList.toArray(new String[stringList.size()]); 

OTHER TIPS

You can use the split(String str) method of class String. Example:

String resultArray[] = stringToSplit.split(",");

Yes, it is quite easy, try this :

    String text = "[title],[description blablablablablabla]";        
    String[] splitted = text.replaceAll("\\[", "").replaceAll("\\]", "").split(",");

To split string you can use this method:

public String[] split(String regex, int limit)

Or

public String[] split(String regex)

For more details visit http://www.tutorialspoint.com/java/java_string_split.htm

Example:

String a = "Hi guys, what's up?"
String[] b = a.split(",");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top