我试图对照词汇表列表检查java字符串,然后如果它找到了词汇表列表中存在的术语,则用标签包装该术语。但是问题是,如果我在词汇表列表中有两个术语:“ Sprint”和“ Sprint 0”,则代码仅选择Sprint术语,而忽略了“ Sprint 0”。
这是我的代码
private String findGlassayTerms(String response, List<Glossary> glossary) {
for (Glossary item : glossary) {
// check if response contains the term
if (StringUtils.contains(response, item.getTerm())) {
System.out.println(item.getTerm());
response = StringUtils.replace(response, item.getTerm(), "<span class=" + item.getTerm() + ">" + item.getTerm() + "</span>");
}
}
return response;
}
结果如下:
<span class=Sprint>Sprint</span> 0 is typically a one or two week period at the end of the Define phase. <br>In summary, <span class=Sprint>Sprint</span> 0 provides an opportunity.
如果List<Glossary> glossary
按术语长度(最长的术语在前)排序,则当前代码应该可以正常工作。另一种解决方案是建立所有匹配项的列表,然后遍历所有匹配项以“打分”正确的匹配项。接下来,我认为您应该将方法重命名为findGlossaryTerms
(而不是findGlassayTerms
)。最后,这种排序(在代码中)可能是这样的-
Collections.sort(glossary, new Comparator<Glossary>() {
public int compare(Glossary a, Glossary b) {
if (a == null) {
if (b == null) {
return 0;
}
return -1;
} else if (b == null) {
return 1;
}
int av = (a.getTerm() != null) ? a.getTerm().length() : 0;
int bv = (b.getTerm() != null) ? b.getTerm().length() : 0;
return Integer.valueOf(bv).compareTo(av);
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句