Anusha Anusha - 7 months ago 17
Java Question

Split a string on reaching certain characters in java

This is my input string

Look - to make links (10) fresh apple (9) This is Apple (7) returns para (6,8) in foot (5)

Expected Output :

Look - to make links (10)

fresh apple (9)

This is Apple (7)

returns para (6,8)

in foot (5)


I want to remove the unwanted strings from the input and need the string as above. I tried splitting using

string.split("(");
but didn't work.

I thought of eliminating all the '()' from the string so it will have only digits. So , how to split and push it to a new line if it contains a digit followed by a space ? For ex :

yy, 2009 Look - to make links


then, the line
"Look - to make links"
must come in next line as there is a digit followed by a space.

NOTE: I want to start reading and manipulating the string only from "2009" . ie. The line "Look - to make links" must be the first line .The String is a dynamic one. So, I can't do an index based calculation.

Any idea of how to do it ?

Answer

It's hard to tell, but it seems this might be what you want:

String[] lines = str.split("(?<=\\))");

This splits after every close bracket, retaining the close bracket. The regex is a look behind, which has the form (?<=...), for a (literal) close bracket. Look aheads/behinds are zero width assertions - so they don't consume any input; essential when you need to split but not lose any of the original content.

Comments