开发者

using regular expressions find phrase in the file

using regular expression for searching phrase in the file

So...

Task:

I have some phrase. the phrase contains 2 words. Phrase is devided into two words with next symbols:

[\s]*

How can i find the phrase using regular expression?

This code doesn't work on a file:
// file: Main.java
    class 


    Main {
    }

program


          Pattern pattern = Pattern.compile("class[\\s]+Main");

          BufferedReader input = new BufferedReader ( new FileReader( "Main.java" ) );

          int id = 0;

          for ( String line = input.readLine(); line != null; line = input.readLine() )
          {
             ++id;

             Matcher matcher = pattern.matcher( line );


             if ( matcher.find() )
      开发者_StackOverflow       {
                System.out.println("number = " + id );

                System.out.println("start = " + matcher.start() );
                System.out.println("end   = " + matcher.end() );
                System.out.println( );
             }
          }

          input.close();


You either need to put the entire file into one string (add the string to a StringBuilder in your for loop, and then do one match on the result at the end), or you need to add a case where you store the last word on one line and the first word on the next line that has any words, and check those also. The easiest but probably not fastest way to do this is something like:

String lastline = ""
// For loop begins
  String[] ll_parts = lastline.split("\\s")
  lastline = line;
  line = ll_parts[ll_parts.length-1] + line;
// Now do the match
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜