【发布时间】:2012-10-27 18:31:15
【问题描述】:
我的程序显示匹配结果,但我想将结果排序为完全匹配(100%)、半匹配等。 我的文本文件包含以下行:
红车
红色
汽车
所以如果我搜索:“红色汽车”。我得到以下结果
红车
红色
汽车
所以我想做的是将找到的结果排序如下:
“红车”100%匹配
“红色”40% 匹配
“汽车”40% 匹配
感谢任何帮助。
感谢任何帮助。我的代码如下:
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());
}
}
【问题讨论】:
-
你能再解释一下逻辑吗?如果您有一行包含“Red or yellow Red Yellow”并且您搜索“Red or yellow”,我希望它在字符串的开头匹配一次。还是您的意思是您正在搜索“红色”或“黄色”,在这种情况下,我希望它匹配 4 次,每种颜色匹配两次 - 但这仍然不是 100%(字符串“或”不匹配)。
-
抱歉文本文件包含三行。第 1 行是“红色或黄色” 第 2 行是“红色”,第三行是“黄色”。第一行是 100% 匹配,所以我想对它们进行排序
-
我很困惑是“或”要匹配的字符串,还是逻辑运算符?如果是要匹配的字符串,则您的第一行匹配 100%,但其他两行根本不匹配。如果是逻辑运算符,那么我不明白为什么第一行是 100%。对不起,如果我错过了明显的
-
你是对的,这是合乎逻辑的。我的例子完全错误,这就是造成混乱的原因。这是真正的问题。文本文件包含:第 1 行是:“红色汽车”。第 2 行是:"red" 第 3 行是"car",所以 red car 将 100% 匹配,而 red 和 car 各 40% 匹配。任何帮助表示赞赏