如何添加一些搜索逻辑

时间:2013-12-11 09:11:02

标签: java

这里我们应该添加那个逻辑而不管字母,在数组argi的这些url中,有一个单词......字符串“word” - 我们在搜索中引入的一个词。请帮助。这是代码:

public class Search {

    private String word;
    private String str="";

            public String getWord() {
            return word;
        }

        public void setWord(String word) {
            this.word = word;
        }
        public String getStr() {
            return str;
        }

        public void setStr(String str) {
            this.str = str;
        }

        private final Pattern TITLE = Pattern.compile("\\<title\\>(.*)\\<\\/title\\>");

        public String search(String url, String someword) {

            try {
                InputStreamReader in = new InputStreamReader(new URL(url).openStream(),"UTF-8");
                StringBuilder input = new StringBuilder();
                int ch;
                while ((ch = in.read()) != -1) {
                    input.append((char) ch);
                }
                if (Pattern.compile(someword).matcher(input).find()) {
                    Matcher title = TITLE.matcher(input);
                    if (title.find()) {
                        return title.group(1);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (PatternSyntaxException e) {
                e.printStackTrace();
            }
            return null;
        }
        public String toString() {
            String[] argi = {"http://localhost:8080/site/endipnagradi", "http://localhost:8080/site/contacts_en", "http://localhost:8080/site/news_en"};

            for (int i = 0; i < argi.length; i++) {
            String result = search(argi[i], word);
            String regex = "^[А-Яа-я]+$";


            if (result != null && word.length()>2) {

                    str += "Search phrase " + "<b>"+ word + "</b>" + " have found in " + "<a href=\"" + argi[i] + "\">" + result + "</a>"+ "<p></p>";

                     }

            if(word.length()<3 || word.matches(regex)){

               str="Word not found!";
             }

            if (word == null || word.isEmpty()) {

                str = "Enter a search word!";

              }
            }
          return null;
    }
}

例如,我把单词“phone”,但我的内容只是单词“Phone”。所以无论如何搜索应该找到它

2 个答案:

答案 0 :(得分:1)

您可以使用equalsIgnoreCase();。然后你就可以有一个解决方案

 "phone".equalsIgnoreCase("Phone") ; // this will return true and found the word

答案 1 :(得分:0)

使用正确的选项创建模式,以便它将执行不区分大小写的匹配。 更改代码:

if (Pattern.compile(someword).matcher(input).find())

if (Pattern.compile(someword, Pattern.CASE_INSENSITIVE).matcher(input).find())

有关详细信息,请查看here