将所有 <BR> 替换为 \n

replaceAll <BR> with \n

我不太擅长正则表达式;因此,我在这里寻求帮助。

我在 Java atm 工作。

我正在寻找的是一段代码,它通过一个字符串并使用 replaceAll()

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

我尝试做的是以下内容 JavaScript replace <br> with \n link 但是通过调试,我可以看到它并没有改变字符串。

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";

有了这两个,我现在用 titleName 字符串创建我的 titleNameRegex 字符串。

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

我也看过 Java regex replaceAll multiline,因为需要不区分大小写,但不确定将标志放在哪里,是 (?i) 吗?

所以我正在寻找的是,我的正则表达式代码应该用 \n
替换所有 <BR><br /> 以便我在 PDF 文档中正确查看。

/<br ?\/?>/ig是Java脚本正则语法,在Java中你需要使用:

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

(?i) 用于忽略大小写比较。

我真的很讨厌正则表达式,这是一门外星语言。但是你想要做的是:

  • 查找(不区分大小写)"<br" 字符串,这样做:(?i)<br
  • 在这个字符串之后找到零个或多个 space,这样做:\p{javaSpaceChar}*
  • 在 space 之后找到 >/>,这样做:(?:/>|>)

所以你在 java 中的最终正则表达式是:

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);

我添加了一些混合大小写 + 超过 1 个 space 以显示所有情况。