By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,294 Members | 2,650 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,294 IT Pros & Developers. It's quick & easy.

Looking for a string in a text file

P: 9
Well I want to search a text file that has some text in it and I want to use a pattern to serach for it. My code does this pretty well for single letters or numbers, but when I try to put in a string "Gus" for instance, it says there are no matches at all even though I know there is at least one Gus in the text file which I attached. At first I thought maybe the break statement is cuaseing the problem, but that is not the case, becuase with out the break statement, it just preints out no match 3 times. What am I doing wrong here am I using the matcher wrong or is it the input or something? thanks for any help with this!
Expand|Select|Wrap|Line Numbers
  1. import java.io.*;
  2. import java.util.Scanner;
  3. import java.util.regex.*;
  4.  
  5. public class SearchTest {
  6.     public static void main(String args[])
  7.     {
  8.         LineNumberReader lineReader = null;
  9.       try {
  10.             String sStr;
  11.             System.out.println("Enter your search term");
  12.             Scanner sScan = new Scanner(System.in);
  13.             sStr = sScan.nextLine();
  14.             Pattern pat = Pattern.compile(sStr, Pattern.CASE_INSENSITIVE);
  15.  
  16.             System.out.println("Your searching for " + pat);
  17.             lineReader = new LineNumberReader( new FileReader("Book-text.txt"));
  18.             String line = null;
  19.  
  20.             while ((line = lineReader.readLine()) != null)
  21.             {
  22.                 Matcher matcher = pat.matcher(line);
  23.  
  24.                 if (matcher.find())
  25.                 {
  26.  
  27.                     String msg = "Found Match "  + line;
  28.                     System.out.println(msg);
  29.  
  30.                 }else{System.out.println("No Matches");}
  31.                 matcher.reset();
  32.             }
  33.  
  34.     }
  35.     catch (FileNotFoundException ex) {
  36.       ex.printStackTrace();
  37.     }
  38.     catch (IOException ex){
  39.       ex.printStackTrace();
  40.     }
  41.     finally {
  42.       try {
  43.         if (lineReader!= null) lineReader.close();
  44.       }
  45.       catch (IOException ex) {
  46.         ex.printStackTrace();
  47.       }
  48.     }
  49.  
  50.  
  51.     }
  52.  
  53. }
  54.  
Attached Files
File Type: txt Book-text.txt (503 Bytes, 281 views)
Feb 17 '11 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.