模式匹配仅关闭单词

时间:2014-08-21 11:38:04

标签: java regex

我有数据库,包含书籍和短语数据库,我尝试生成HTML文件。为简单起见,我想说我想大胆一些短语。

我有以下句子:

Following that mission I was sent on further missions. Most of them succeeded and we are living with the consequences today. They must remain secret. If the truth ever came out, then some of the national leaders at the time would find themselves in the Hague on war crimes charges.

我想做出大胆的使命 - 这很简单。我用于模式唯一的任务词。 但有时短语的单词并不是彼此相邻的。在例句中它是'收费' 所以我想出我可以放入数据库通配符,我将在稍后的程序中替换它。所以在数据库中它是'on%charge' 另外,我不希望将不是短语部分的单词加粗。

所以输出应该是

<b>on</b> war crime <b>charges</b>

我的Java代码如下所示(w.getWord()返回'%charge'

String pat = w.getWord().replace("%", ".+?").trim();
Pattern p = Pattern.compile("(\\W)(" + pat + "){1}?(\\W)");
text = text.replaceFirst(p.pattern(), "$1<b>$2</b>$3");

现在,在那句话中,问题出现了,如果在句子之前还有另一个问题,它会加粗到粗体输出:

Following that mission I was sent <b>on further missions. Most of them succeeded and we are living with the consequences today. They must remain secret. If the truth ever came out, then some of the national leaders at the time would find themselves in the Hague on war crimes charges</b>

0 个答案:

没有答案