Java 如何添加一些搜索逻辑
在这里,我们应该添加逻辑,无论字母是什么,在数组argi的url中,有一个特定的单词。。。字符串“word”-我们在搜索中引入的一个单词。请提供帮助。以下是代码:Java 如何添加一些搜索逻辑,java,Java,在这里,我们应该添加逻辑,无论字母是什么,在数组argi的url中,有一个特定的单词。。。字符串“word”-我们在搜索中引入的一个单词。请提供帮助。以下是代码: public class Search { private String word; private String str=""; public String getWord() { return word; } public voi
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;
}
}
公共类搜索{
私有字符串字;
私有字符串str=“”;
公共字符串getWord(){
返回词;
}
公共无效设置字(字符串字){
这个单词=单词;
}
公共字符串getStr(){
返回str;
}
公共void setStr(字符串str){
this.str=str;
}
私有最终模式标题=Pattern.compile(“\\(.*)\\”;
公共字符串搜索(字符串url、字符串someword){
试一试{
InputStreamReader in=新的InputStreamReader(新的URL(URL).openStream(),“UTF-8”);
StringBuilder输入=新建StringBuilder();
int-ch;
而((ch=in.read())!=-1){
input.append((char)ch);
}
if(Pattern.compile(someword).matcher(input.find()){
Matcher title=title.Matcher(输入);
if(title.find()){
返回标题。组(1);
}
}
}捕获(IOE异常){
e、 printStackTrace();
}捕获(模式语法异常e){
e、 printStackTrace();
}
返回null;
}
公共字符串toString(){
字符串[]argi={”http://localhost:8080/site/endipnagradi", "http://localhost:8080/site/contacts_en", "http://localhost:8080/site/news_en"};
for(int i=0;i2){
str+=“搜索短语”+“+word++”已在“+””中找到;
}
如果(word.length()可以使用equalsIgnoreCase();
,那么就可以找到解决方案
"phone".equalsIgnoreCase("Phone") ; // this will return true and found the word
使用正确的选项创建您的模式,以便它进行不区分大小写的匹配。
将代码更改为:
if (Pattern.compile(someword).matcher(input).find())
到
要了解更多信息,请查看。但我有可变字符串word。如何将其添加到我的代码中?太好了,很有用!!谢谢!
if (Pattern.compile(someword, Pattern.CASE_INSENSITIVE).matcher(input).find())