如何在Java中使用不区分大小写的RegEx?

时间:2016-10-24 11:20:47

标签: java regex

我有一个私人方法,用于使用RegEx查找药物名称。代码如下,

private boolean containsExactDrugName(String testString, String drugName) {

    int begin = -1;
    int end = -1;

    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;
}

它应该采用药物名称并在文本字符串中找到完全匹配。这意味着如果药品名称为insuline且字符串文本为The patient is taking insulineee for the treatment of diabetes,则会中断。它需要The patient is taking insuline for the treatment of diabetes的完全匹配。

但是,我还需要不区分大小写的匹配项,如果文本为The patient is taking Insuline for the treatment of diabetesThe patient is taking INSULINE for the treatment of diabetes,则该方法也应返回true

我将Pattern.CASE_INSENSITIVE放在代码中,然而,它并不起作用。如何正确编写?

1 个答案:

答案 0 :(得分:4)

@Chaklader

Pattern.CASE_INSENSITIVE是我所知道的方法。它应该工作。 仅用于ASCII不区分大小写的匹配

Pattern p = Pattern.compile("YOUR_REGEX GOES HERE", Pattern.CASE_INSENSITIVE);

或用于Unicode案例折叠匹配

Pattern p = Pattern.compile("YOUR_REGEX GOES HERE", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);