Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract a string between two delimiters [duplicate]

Tags:

java

string

split

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?

like image 870
yogsma Avatar asked Dec 10 '12 07:12

yogsma


People also ask

How do I extract text between two delimiters?

The easiest way to extract a substring between two delimiters is to use the text to column feature in Excel, especially if you have multiple delimiters. In this example, use =MID(A2, SEARCH(“-“,A2) + 1, SEARCH(“-“,A2,SEARCH(“-“,A2)+1) – SEARCH(“-“,A2) – 1) in cell B2 and drag it to the entire data range.

How do I extract a string between two delimiters in SQL Server?

If you're using SQL Server 2016 or newer you can use the STRING_SPLIT function. @squillman I am using SQL Server 2014. You can use a string splitting function.

How do I extract a string between two delimiters in Python?

The Python standard library comes with a function for splitting strings: the split() function. This function can be used to split strings between characters. The split() function takes two parameters.

How do I extract text between two instances of a character?

Select a cell which you will place the result, type this formula =MID(LEFT(A1,FIND(">",A1)-1),FIND("<",A1)+1,LEN(A1)), and press Enter key. Note: A1 is the text cell, > and < are the two characters you want to extract string between.


2 Answers

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("]")); 
like image 189
Juvanis Avatar answered Sep 24 '22 08:09

Juvanis


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 } 
like image 37
shift66 Avatar answered Sep 20 '22 08:09

shift66