简体   繁体   中英

Regular expression is not working java.util.regex.*;

I am having problems when I implement Regular Expressions in my code...

I'll give a quick explanation of it... I have a function that receives a String to check if that String contains an element of an ArrayList (these elements can be of one or more words). If it doesn't contain any element of the list then it returns to write it to a file otherwise is ignored. First I did the following:

private boolean containDiscontinuedWord(String query) {
Matcher matcher;
Pattern pattern;
    for (String blackL : blackList) {
        pattern = Pattern.compile("\\b" + blackL + "\\b");
        matcher = pattern.matcher(query);
            while(matcher.find()) {
                return true;
            }
    }
    return false;
}

The problem I have here is that when I run the application under a linux environment(jvm 1.5 installed) then nothing is written to the file... but it does under windows environment . My application is built with 1.6 with 1.5 compatibility.

So I did the following:

private boolean containDiscontinuedWord(String query) {
    for (String blackL : blackList) {
        if(query.matches(".*\\b(" + blackL + ")\\b.*")){
            return true;
        }
    }
    return false;
}

And this function works just fine but without the "*" of my regular expression...but that I need to use for the exact match, but again it runs fine under windows environment. I have searched about this in so many ways but I just can't find something that fixes this problem, I don't know if my regular expression is not correct or what can be... I hope you guys can give me a clue!

My apologies if this is a dumb question, but Thanks a lot for reading it!

You seriously need to investigate indexOf . The way you are building the regexp is already very error-prone (think about quoting). Plus, you did not understand the difference between "matching" and "searching" with regexps.

What are your black listed words? If they contain any regex meta-characters they will need to be quoted.

http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#quote%28java.lang.String%29

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM