【问题标题】:Pattern not matching all phrase in a text file模式不匹配文本文件中的所有短语
【发布时间】:2012-11-08 21:41:29
【问题描述】:

我的程序未显示所需的匹配结果。我的文本文件包含以下行:

  1. 红车
  2. 蓝色或红色
  3. 红色
  4. 汽车

所以如果我搜索:“红色汽车”。我只得到“红车”作为唯一的结果,但我想要的是得到以下结果:

  1. 红车
  2. 红色
  3. 红色
  4. 汽车

因为这些字符串在文本文件中。蓝色或红色,“或”是合乎逻辑的。所以我想匹配它们中的任何一个而不是两者。我究竟做错了什么? 任何帮助表示赞赏。我的代码如下:

    public static void main(String[] args) {
        // TODO code application logic here
        //String key;
        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 = 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.start() + " " + 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());
    }
   }
 }

【问题讨论】:

  • 你传递了什么正则表达式作为输入?
  • 这就是为什么你只得到了“红车”
  • 那么您希望空格字符被视为搜索的 OR 运算符吗?
  • 文本文件包含“Red Car”、“Red”、“Red or Blue”和“Car”。为什么我只得到一辆红色汽车作为唯一的结果。如果我乘坐红车并匹配红车的第一串。那是100%的匹配。如果我将它与下一个字符串进行比较,那么这就是 Red 一词的匹配项。我想显示所有的比赛,包括像“红色”或“汽车”这样的半场比赛
  • 是的字符串“蓝色或红色”我想显示红色或蓝色,如果两个词都存在于我的文本文件中,我也想显示它们。

标签: java pattern-matching


【解决方案1】:

尝试传递这个正则表达式:-

"((?:Red)?\\s*(?:or)?\\s*(?:Car)?)"

这将匹配:-

0 or 1红色后跟0 or more空格后跟0 or 1汽车

(?:...) 是非捕获组

注意:-上述正则表达式不匹配:-Car Red

如果您的订单可以反转,那么您可以使用:-

"((?:Red|Car)?\\s*(?:or)?\\s*(?:Red|Car)?)"

并从group(0)获取完整匹配。

例如:-

String strLine = "Car or Red";
Pattern p = Pattern.compile("((?:Red|Car)?\\s*(?:or)?\\s*(?:Red|Car)?)"); 
Matcher m = p.matcher(strLine);  // src of text to search

if (m.matches()) {  
    System.out.println(m.group()); // returns index and match
}

输出:-

Car or Red

将您的while(b = m.find()) 替换为if (m.matches()),因为您想匹配完整的字符串,并且只匹配一次。

【讨论】:

  • 你试过从键盘传递这个正则表达式吗?
  • @SalimShari.. 如果您从键盘传递您的正则表达式,那么只需使用单反斜杠作为您的空间。通过: - ((?:Red|Car)?\s*(?:or)?\s*(?:Red|Car)?) 作为输入。
【解决方案2】:

你的模式应该是Red|Car

【讨论】:

  • 还是不行。它可以匹配RedCar。但不是两者兼而有之。这是必需的。看我的回答。
  • 它将匹配字符串。你的答案太复杂了。
  • 你的模式意味着match either Red or Car。现在它适用于Red Car,以防您使用find,但不适用于您使用match。我的意思是它不会完全匹配。
  • 我的回答怎么让你觉得很复杂?我认为这个正则表达式很简单。复杂的不适合它。
  • 哦,别无聊,你懂我的意思。
猜你喜欢
  • 1970-01-01
  • 2022-11-17
  • 2018-04-21
  • 2020-07-23
  • 1970-01-01
  • 2018-07-05
  • 1970-01-01
  • 1970-01-01
  • 2011-06-05
相关资源
最近更新 更多