简体   繁体   中英

replaceAll <BR> with \n

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.

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

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

(?i) is for ignore case comparison.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM