正则表达式不匹配短语中的子词

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

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

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()); } } 

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

 Pattern p = Pattern.compile(key); Matcher m = p.matcher(strLine);