2012-11-08 41 views
0

我的程序未显示所需的匹配结果。我的文本文件包含以下行:模式不匹配文本文件中的所有短语

  1. 红车
  2. 蓝色或红色

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

  1. 红车

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

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

你输入的是什么正则表达式? –

+0

我输入的“红色车” –

+2

这就是为什么你只有“红色车”回 –

回答

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)采取完全匹配。

E.g: -

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()),只要你想匹配的完整的字符串,并且只有一次。

+0

没有为我工作 –

+0

对于哪个输入? –

+0

它为我工作。你用什么字符串匹配它? –

-1

你的模式应该是Red|Car

+1

这不匹配'红车' –

+0

是的,组的将是错误的,让我修复那 – unbeli

+0

现在它会。呵呵 – unbeli

相关问题