1

我的程序显示匹配结果,但我想将结果排序为最佳匹配、次佳匹配等等。

我的文本文件包含以下行:

red or yellow red' 黄色'

所以如果我搜索red or yellow::我得到以下结果 'red or yellow red yellow。所以我想要做的是将找到的结果排序如下:

  1. “红黄”100%匹配
  2. “红色” 40% 匹配
  3. “黄色” 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());
  }
}
4

1 回答 1

2

您有混合模式和搜索空间。行 ( strLine) 是您的搜索空间并且key是模式。使固定:

Pattern p = Pattern.compile(key);
Matcher m = p.matcher(strLine);
于 2012-11-07T15:41:47.540 回答