【发布时间】:2014-03-10 13:44:12
【问题描述】:
我正在处理包含图像标签和新行标签的文本段落。目标是通过将所有单词字符的颜色更改为白色来清楚地显示所有非单词字符。 我使用java作为编程语言。 我正在尝试使用正则表达式,但 问题 是 它会更改图像标签内的单词字符。
String RegEx = "\\w|[àÀâÂäÄáÁéÉèÈêÊëËìÌîÎïÏòÒôÔöÖùÙûÛüÜçÇ’ñ]";
try {
Pattern mypattern = Pattern.compile(RegEx, Pattern.CASE_INSENSITIVE);
Matcher myMatcher = mypattern.matcher(sentence);
int offset = 0;
while (myMatcher.find()) {
int start = myMatcher.start() + offset;
int end = myMatcher.end() + offset;
sentence = sentence.substring(0, start) + "<font color=\"white\">" + sentence.substring(start, end) + "</font>" + sentence.substring(end, sentence.length());
offset += 28;
}
} catch (Exception e) {
e.printStackTrace();
}
所需结果的示例。
输入:
Most implementations<img title="hello:" alt="hello:{}" src="http://images.doctissimo.fr/hello.gif" class="wysiwyg_smiley" /> provide ASDF as a module, and you can simply (require "asdf").
输出:
<font color="white">Most<font> <font color="white">implementations<font><img title="hello:" alt="hello:{}" src="http://images.doctissimo.fr/hello.gif" class="wysiwyg_smiley" /> <font color="white">provide<font> <font color="white">ASDF<font> <font color="white">as<font> <font color="white">a<font> <font color="white">module<font>, <font color="white">and<font> <font color="white">you<font> <font color="white">can<font> <font color="white">simply<font> (<font color="white">require<font> "<font color="white">asdf<font>").
【问题讨论】:
-
使用 HTML 解析器/生成器!
-
您无法使用 RegEx 解析 HTML。每次你尝试时,一个无所不能的抽象和独立于宗教的实体都会杀死一只小猫。
-
你能看看JSoup吗?它可能会帮助你。 jsoup.org
-
@Kroltan 太好了,你让我很开心。 ;)
-
看看这个解决方案:stackoverflow.com/a/21731443/363573