How to extract a string between two delimiters

JavaStringSplit

Java Problem Overview


> Possible Duplicate:
> substring between two delimiters

I have a string like

> "ABC[ This is to extract ]"

I want to extract the part "This is to extract" in java. I am trying to use split, but it is not working the way I want. Does anyone have suggestion?

Java Solutions


Solution 1 - Java

If you have just a pair of brackets ( [] ) in your string, you can use indexOf():

String str = "ABC[ This is the text to be extracted ]";    
String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));

Solution 2 - Java

If there is only 1 occurrence, the answer of ivanovic is the best way I guess. But if there are many occurrences, you should use regexp:

\[(.*?)\] this is your pattern. And in each group(1) will get you your string.

Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(input);
while(m.find())
{
	m.group(1); //is your string. do what you want
}

Solution 3 - Java

Try as

String s = "ABC[ This is to extract ]";
		Pattern p = Pattern.compile(".*\\[ *(.*) *\\].*");
		Matcher m = p.matcher(s);
		m.find();
		String text = m.group(1);
		System.out.println(text);

Solution 4 - Java

  String s = "ABC[This is to extract]";

	System.out.println(s);
	int startIndex = s.indexOf('[');
	System.out.println("indexOf([) = " + startIndex);
	int endIndex = s.indexOf(']');
	System.out.println("indexOf(]) = " + endIndex);
	System.out.println(s.substring(startIndex + 1, endIndex));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionyogsmaView Question on Stackoverflow
Solution 1 - JavaJuvanisView Answer on Stackoverflow
Solution 2 - Javashift66View Answer on Stackoverflow
Solution 3 - JavaEvgeniy DorofeevView Answer on Stackoverflow
Solution 4 - JavaMilanPanchalView Answer on Stackoverflow