我是Android和Java的新手所以请你好:)
我的EditText应用程序中有一个用于搜索a中的特定字符串String[]
我的代码运行良好,但不是我想要的:
ArrayList<String> allProd = new ArrayList<String>;
ArrayList<String> allProd_sort = new ArrayList<String>;
allProd = [the table is brown, the cat is red, the dog is white];
String[] allProdString = allProd.toArray(new String[allProd.size()]);
...
//inputSearch is the EditText
inputSearch.addTextChangeListener (new TextWatcher() {
...
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
int textLength = inputSearch.getText().length();
String text = inputSearch.getText().toString();
for (int y = 0; y< allProdString.length; y++) {
//in my case i want that the search start when there are min 3 characters in inputSearch
if(textLength <= allProdString[y].length() && textLength >=3) {
if (Pattern.compile(Pattern.quote(text), Pattern.CASE_INSENSITIVE)
.matcher(allProdString[y]).find()) {
allProd_sort.add(allProdString[y]);
}
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
此代码生成以下结果:
如果我搜索"table is"=> allProd_sort将会[the table is brown]
但如果我搜索"table brown"=> allProd_sort将是空的但我想要[the table is brown]
我怎么能改善这个?
谢谢大家
好的 - 第一次优化:仅当您的初始要求(Searchtext >=3)为真时才进入循环:
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
int textLength = inputSearch.getText().length();
if (textLength < 3) return;
String[] searchPattern = inputSearch.getText().toString().toLowerCase().split("\\s+");
for (int y = 0; y< allProdString.length; y++) {
if(textLength <= allProdString[y].length()) {
if (matchSearch(allProdString[y].toLowerCase(), searchPattern)) {
allProd_sort.add(allProdString[y]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您只想匹配所有单词都包含在同一序列中的行,您可以简单地创建一个正则表达式,如 Tim B 所说。
但是,如果您还想匹配包含任意位置搜索“brown table”-> [the table is Brown] 单词的字符串,那么您需要一个小循环:
public boolean matchSearch(String s, String[] searches) {
for (String search : searches) {
if (!s.contains(search) return false; // If the word is not in the string FALSE
}
return true; // If all words were found in the string, it is a match!
}
Run Code Online (Sandbox Code Playgroud)
为了使这一点更清楚 -> Brown.*table 只会匹配 table 在 Brown 之后的字符串...我认为您无法轻松创建一个有效的正则表达式来检查每个单词是否在字符串中的任何位置至少出现一次...
| 归档时间: |
|
| 查看次数: |
141 次 |
| 最近记录: |