Looking for a string in a text file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kakashi
    New Member
    • Oct 2009
    • 9

    Looking for a string in a text file

    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!
    Code:
    import java.io.*;
    import java.util.Scanner;
    import java.util.regex.*;
    
    public class SearchTest {
        public static void main(String args[])
        {
            LineNumberReader lineReader = null;
          try {
                String sStr;
                System.out.println("Enter your search term");
                Scanner sScan = new Scanner(System.in);
                sStr = sScan.nextLine();
                Pattern pat = Pattern.compile(sStr, Pattern.CASE_INSENSITIVE);
    
                System.out.println("Your searching for " + pat);
                lineReader = new LineNumberReader( new FileReader("Book-text.txt"));
                String line = null;
    
                while ((line = lineReader.readLine()) != null)
                {
                    Matcher matcher = pat.matcher(line);
    
                    if (matcher.find())
                    {
                        
                        String msg = "Found Match "  + line;
                        System.out.println(msg);
    
                    }else{System.out.println("No Matches");}
                    matcher.reset();
                }
    
        }
        catch (FileNotFoundException ex) {
          ex.printStackTrace();
        }
        catch (IOException ex){
          ex.printStackTrace();
        }
        finally {
          try {
            if (lineReader!= null) lineReader.close();
          }
          catch (IOException ex) {
            ex.printStackTrace();
          }
        }
    
    
        }
    
    }
    Attached Files
Working...