我的程序显示匹配的结果,但我想将结果排序为最佳匹配,第二最佳匹配等等。
我的文本文件包含以下行:
red or yellow
red'
黄色“
所以如果我搜索:red or yellow
:我得到以下结果
'red or yellow
red
yellow
。
所以我想要做的是按如下方式对找到的结果进行排序:
感谢任何帮助。我的代码如下:
public static void main(String[] args) {
// TODO code application logic here
String strLine;
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C:\\textfile.txt"");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Scanner input = new Scanner (System.in);
System.out.print("Enter Your Search: "); // String key="red or yellow";
String key = input.nextLine();
while ((strLine = br.readLine()) != null) {
Pattern p = Pattern.compile(key); // regex pattern to search for
Matcher m = p.matcher(strLine); // src of text to search
boolean b = false;
while(b = m.find()) {
System.out.println( " " + m.group()); // returns index and match
// Print the content on the console
}
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
答案 0 :(得分:2)
您有混合模式和搜索空间。行(strLine
)是您的搜索空间,key
是模式。修正:
Pattern p = Pattern.compile(key);
Matcher m = p.matcher(strLine);