2

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.

Community
  • 1
  • 1
Jesper
  • 119
  • 1
  • 3
  • 15

2 Answers2

3

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

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

(?i) is for ignore case comparison.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • So what I have written in Javascript regex, is the same as what you have written in Java regex? – Jesper Jun 18 '15 at 08:56
  • Yes definitely it is same and much simpler than the answer you've marked as accepted. [You can see this demo](https://regex101.com/r/xK8sB3/1) – anubhava Jun 18 '15 at 10:14
1

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.

TrapII
  • 2,219
  • 1
  • 15
  • 15