正则表达式与词组中的子词不匹配 [英] Regular expression not matching subwords in phrase

查看:47
本文介绍了正则表达式与词组中的子词不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序显示匹配结果,但是我想将结果按最佳匹配,次最佳匹配之类排序.

My program displays the matching results, but I want to sort the results as best match, second best match ans so on.

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

My text file contains the following line:

红色或黄色 red'黄色"

因此,如果我搜索:红色或黄色:我得到以下结果'红色或黄色 red yellow .所以我要做的是对找到的结果进行如下排序:

So If I search for: red or yellow: I get the following results 'red or yellow red yellow. So what I want to do is to sort the found results as follows:

  1. 红色和黄色" 100%匹配
  2. 红色" 40%匹配
  3. 黄色" 40%匹配

感谢您的帮助.我的代码如下:

Any help is appreciated. My code is as follows:

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 是该模式.修复:

You have mixed pattern and search space. The line (strLine) is your search space and key is the pattern. Fix:

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

这篇关于正则表达式与词组中的子词不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆