My problem here is that i want a Character remove in some parts of a String but I do not know how to restrict the removing.
Example:
A computer is a general purpose device that can be\n
programmed to carry out a finite set of\n
millions to billions of times more capable.\n
\n
In this era mechanical analog computers were used\n
for military applications.\n
1.1 Limited-function early computers\n
1.2 First general-purpose computers\n
1.3 Stored-program architecture\n
1.4 Semiconductors and\n
this here example is the content of my string, what i want to happen is to remove the \n of lines 1 and 2 above but not to remove the \n in line 5 onwards. How do i remove the \n without removing the other \n?. My Goal here is to make the string a paragraph without \n after line. like the example the first 3 lines can be a paragraph and the next lines are in bullet form(example). what i am saying is that I do not want to remove \n in bulleted characters.
The real contents of the string is dynamic.
I have tried using String.replaceAll("\n", " ") well clearly that would not work it will remove all the \n i have thought of using Regex to determine what is Alphanumberic but it would remove some letters after \n
Try using this regex: –
This will replace your
\nif it isnot precededby adot - termination of a paragraph, and it isnot followedby adigit, for when it is followed by a bulleted point. (like, your\nin first bullet point is followed by a1.2. So, it will not be replaced.).(.+)at the start, ensures that you are not replacing ablank line.This will work for the string you have shown.
Explanation: –
(.+)-> A capture group, capturing anything, occurring at least once.(?<!\\.)-> This is callednegative-look-behind. It matches thestringfollowing it, only if that string is not preceded by adot(.)given in thenegative-look-behindpattern.For e.g.: – You don’t need to replace
\nafter the line: –millions to billions of times more capable.\n.(?!\\d)-> This is callednegative -look-ahead. It matches string behind it, only if that string is not followed by adigit (\\d)given in thenegative-look-aheadpattern.For e.g.: – In your bulleted points,
computers\nis followed by1.2. where1is a digit. So, you don’t want to replace that\n.Now,
$1and$2represent the groups captured in the pattern match. Since you just want to replace"\n". So, we took the remaining pattern match as it is, while replacing"\n"with aspace.So,
$1is representation for1st group–(.+)Note,
look-aheadandlook-behindregexes arenon-capturinggroups.For More Details, follow these links: –
http://docs.oracle.com/javase/tutorial/essential/regex/
http://docs.oracle.com/javase/tutorial/essential/regex/quant.html