【发布时间】:2012-11-08 21:41:29
【问题描述】:
我的程序未显示所需的匹配结果。我的文本文件包含以下行:
- 红车
- 蓝色或红色
- 红色
- 汽车
所以如果我搜索:“红色汽车”。我只得到“红车”作为唯一的结果,但我想要的是得到以下结果:
- 红车
- 红色
- 红色
- 汽车
因为这些字符串在文本文件中。蓝色或红色,“或”是合乎逻辑的。所以我想匹配它们中的任何一个而不是两者。我究竟做错了什么? 任何帮助表示赞赏。我的代码如下:
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