replaceAll <BR> with \n

8k views Asked by At

I am not very good in the ways of Regex; therefor I am here to get help.

I am working in Java atm.

What I am looking for is a piece of code, that goes through a String and uses replaceAll()

The tags I want to change from and to:
replaceAll() : <BR>, <br>, <br /> or/and <BR /> with “\n”

What I have tried to do, is the following from this JavaScript replace <br> with \n link but from debugging, I can see that it, doesn’t change the String.

MyCode

String titleName = model.getText();

// this Gives me the string comprised of different values, all Strings.

countryName<BR> dateFrom - dateTo: - \n hotelName <br />

// for easy overview I have created to variables, with the following values

String patternRegex = "/<br ?\\/?>/ig";
String newline = "\n";

With these two, I now create my titleNameRegex string, with the titleName String.

String titleNameRegex = titleName.replaceAll(patternRegex, newline);

I have had a look at Java regex replaceAll multiline as well, because of the need to be case insensitive, but unsure where to put the flag for this and is it (?i) ?

So what I am looking for, is that my regex code should, replaceAll <BR> and <br /> with \n,
so that i looks properly in my PDF document.

2

There are 2 answers

2
anubhava On BEST ANSWER

/<br ?\\/?>/ig is Javascript regex syntax, in Java you need to use:

String patternRegex = "(?i)<br */?>";

(?i) is for ignore case comparison.

0
TrapII On

I really hate regexp this is an alien language. But what you are trying to do is :

  • Look (case insensitive) for a "<br" string, done like that : (?i)<br
  • After this string find zero or more space, done like that : \\p{javaSpaceChar}*
  • After the spaces find either > or />, done like that : (?:/>|>)

So your final regexp in java is :

String titleName = "countryName<BR/> dateFrom <Br    >- dateTo: - <br/> hotelName <br  />";
String patternRegex = "(?i)<br\\p{javaSpaceChar}*(?:/>|>)";
String newline = "\n";
String titleNameRegex = titleName.replaceAll(patternRegex, newline);

I added some mixed case + more than 1 space to show all cases.