简体   繁体   English

正则表达式不起作用java.util.regex。*;

[英]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). 我将对其进行快速解释...我有一个函数,该函数接收一个String来检查String是否包含ArrayList的元素(这些元素可以是一个或多个单词)。 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 . 我这里的问题是,当我在linux环境(安装了jvm 1.5)下运行应用程序时,什么都没有写到文件中……但是在Windows环境下却可以 My application is built with 1.6 with 1.5 compatibility. 我的应用程序是使用具有1.5兼容性的1.6构建的。

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. 而且此函数可以正常工作,但没有正则表达式的“ *” ...但是我需要使用它来进行精确匹配,但再次在Windows环境下运行良好。 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 . 您非常需要调查indexOf The way you are building the regexp is already very error-prone (think about quoting). 构建regexp的方式已经很容易出错(考虑引用)。 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 http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#quote%28java.lang.String%29

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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