gpt4 book ai didi

java - 如何更正正则表达式以在不区分大小写的情况下找到精确的单词匹配?

转载 作者:行者123 更新时间:2023-11-29 04:38:31 30 4
gpt4 key购买 nike

我有一个正在测试并在下面提供的私有(private)方法,

private boolean containsExactDrugName(String testString, String drugName) {

Matcher m = Pattern.compile("\\b(?:" + drugName + ")\\b|\\S+", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE).matcher(testString);
ArrayList<String> results = new ArrayList<>();

while (m.find()) {
results.add(m.group());
}

boolean found = results.contains(drugName);
return found;
}

我采用方法中提供的文本 String 和药物名称,并返回 boolean。我需要它是大小写 insensitive 并且测试的最后一个 assertion 失败。下面提供了测试,

@Test
public void test_getRiskFactors_givenTextWith_Orlistat_Should_Not_Find_Medication() throws Exception {

String drugName = "Orlistat";
assertEquals("With Orlistat", true, containsExactDrugName("The patient is currently being treated with Orlistat", drugName));
assertEquals("With Orlistattesee", false, containsExactDrugName("The patient is currently being treated with Orlistattesee", drugName));
assertEquals("With abcOrlistat", false, containsExactDrugName("The patient is currently being treated with abcOrlistat", drugName));
assertEquals("With orlistat", true, containsExactDrugName("The patient is currently being treated with orlistat", drugName));
}

在最后一个断言中,药物名称是小写的 orlistat 但仍需要与提供的参数 Orlistat 匹配。我使用了 Pattern.CASE_INSENSITIVE,但它不起作用。如何正确编写代码?

最佳答案

问题主要不在于您的正则表达式,而在于 containsExactDrugName 方法本身。您正在进行不区分大小写的匹配以在较大的字符串中查找 drugName,但随后您在其中查找 drugName精确匹配匹配字符串的结果列表:

results.contains(drugName)

此检查不仅是多余的(因为正则表达式已经完成了查找匹配项的工作),它还主动破坏了您的功能,因为您再次检查了精确的、区分大小写的匹配项。简单地摆脱它:

private boolean containsExactDrugName(String testString, String drugName) {

Matcher m = Pattern.compile("\\b(?:" + drugName + ")\\b", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE).matcher(testString);
List<String> results = new ArrayList<>();

while (m.find()) {
results.add(m.group());
}

return !results.isEmpty();
}

实际上,由于您没有记录找到 drugName 的次数,因此整个列表毫无意义,您可以将方法简化为:

private boolean containsExactDrugName(String testString, String drugName) {

Matcher m = Pattern.compile("\\b(?:" + drugName + ")\\b", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE).matcher(testString);

return m.find();
}

编辑 - 您的正则表达式也过于宽松。它匹配 \\S+,这意味着 1 个或多个非空格字符的任何序列。我不确定您为什么包含它,但它会导致您的正则表达式匹配不是 drugName 的内容。删除表达式的 |\\S+ 部分。

关于java - 如何更正正则表达式以在不区分大小写的情况下找到精确的单词匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40231965/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com