How to do case insensitive RegEx in Java? [duplicate]

删除回忆录丶 提交于 2021-02-17 07:19:06

问题


I have a private method that I use for finding drug name using RegEx. The code is as following,

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

It should take a drug name and finds exact match inside the text String. That means if the drug name is insuline and the the String text is The patient is taking insulineee for the treatment of diabetes, it will break. It will need the exact match of The patient is taking insuline for the treatment of diabetes.

However, I also need case insensitive matches and if the text is The patient is taking Insuline for the treatment of diabetes or The patient is taking INSULINE for the treatment of diabetes, the method should return true as well.

I put the Pattern.CASE_INSENSITIVE inside the code, however, it doesn't work. How to write it properly ?


回答1:


@Chaklader

Pattern.CASE_INSENSITIVE is the method I'm known to. It should work. for ASCII only case-insensitive matching

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

or for Unicode case-folding matching

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


来源:https://stackoverflow.com/questions/40217094/how-to-do-case-insensitive-regex-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!