替换所有<br/>与\ n

时间:2015-06-18 08:50:16

标签: java regex replace replaceall

我对正则表达方式不是很了解;因为我在这里得到帮助。

我在Java atm工作。

我正在寻找的是一段代码,通过String并使用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 String创建我的titleNameRegex字符串。

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

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

所以我要找的是,我的正则表达式代码应该用<BR>替换所有<br />\n, 所以我在我的PDF文档中看得很清楚。

2 个答案:

答案 0 :(得分:3)

<a href="http"//stackoverflow.com">http://stackoverflow.com</a>是Javascript正则表达式语法,在Java中需要使用:

/<br ?\\/?>/ig

String patternRegex = "(?i)<br */?>"; 用于忽略大小写比较。

答案 1 :(得分:1)

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

  • 查看(不区分大小写)"<br"字符串,完成如下操作:(?i)<br
  • 在此字符串找到零个或多个空格后,执行如下操作:\\p{javaSpaceChar}*
  • 在空格找到>/>之后,就像这样做:(?:/>|>)

所以你在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个空格来显示所有情况。

相关问题