【问题标题】:Regular expression not matching subwords in phrase正则表达式与短语中的子词不匹配
【发布时间】:2012-11-07 15:38:19
【问题描述】:

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

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

red or yellow red' yellow'

所以如果我搜索: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());
  }
}

【问题讨论】:

  • 供将来参考 - 在问题标题中描述您的问题。诸如“我有问题”之类的标题或其派生词对路过的读者没有帮助!

标签: java regex


【解决方案1】:

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

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

【讨论】:

  • 谢谢,我的问题解决了一半。
  • 我想对找到的结果进行如下排序: 1."red and yellow" 100% 匹配 2."red" 40% 匹配 3."yellow" 40% 匹配 任何帮助,你已经排序通过指出我的愚蠢错误来解决我的一半问题。我很感谢你。
  • 请提出一个新问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-17
  • 2016-12-26
  • 1970-01-01
  • 2018-05-18
  • 2013-01-04
  • 2015-09-24
  • 1970-01-01
相关资源
最近更新 更多