自近幾天來我一直在做這件事,但仍然無法獲得所需的輸出。 那麼我有一個數組說 wordlist[]={"One","Two","Three","Four","Five"};
然後我從用戶的輸入。在輸入字符串中搜索數組中的關鍵字並打印它們
String input="I have three no, four strings";
現在我想做的事是要檢查的字符串在單詞表數組[]提供的詞進行搜索操作; 就像在上面的例子中,輸入字符串包含數組中存在的三個和四個字。 所以它應該能夠打印字符串中可用數組中的那些單詞,並且如果沒有來自單詞表[]的單詞可用,那麼它應該打印「找不到匹配單詞」。
這是我的代碼,我很震驚。 請
import java.util.regex.*;
import java.io.*;
class StringSearch{
public static void main(String ...v)throws IOException{
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
String wordlist[]={"one","two","three","four","five"};
String input=cin.readLine();
int i,j;
boolean found;
Pattern pat;
Matcher mat;
Pattern spliter=Pattern.compile("[ ,.!]");
String ip[]=spliter.split(input);
System.out.println(ip[2]);
for(i=0; i<wordlist.length;i++){
for(j=0;j<ip.length;j++){
pat=Pattern.compile("\b"+ip[j]+"\b");
mat=pat.matcher(wordlist[i]);
if(){
// No Idea What to write here
}
}
}
}
}
在if條件中放了'mat.matches()'。在if體內增加一個計數整數,並在for循環之外使用它來打印「找不到匹配」,以防零匹配。也檢查''\ b「+ ip [j] +」\ b「'正則表達式,它對我不起作用 – Oneiros
@Oneiros'匹配'添加'^'和'$'所以它應該是完全匹配 –