2009-06-18 4 views
2

java에서 나는 한 줄씩 파일을 읽고 그 출력에 줄을 인쇄하고 싶다. 정규식으로이를 해결하고자합니다.java regex line

while (...) 
{ 
    private static java.util.regex.Pattern line = java.util.regex.Pattern.compile(".*\\n"); 
    System.out.print(scanner.next(line)); 
} 

코드의 정규식이 올바르지 않습니다. InputMismatchException이 발생합니다. 2 시간 동안이 정규식에서 작업하고 있습니다. 제발 도와주세요.

regex powertoy에서 ". * \ n"이 정확한지 확인하십시오. 하지만 내 프로그램이 잘못 실행됩니다.

전체 소스는 : 예를 들어 입력

/** 
* Extracts the points in the standard input in off file format to the standard output in ascii points format. 
*/ 

import java.util.regex.Pattern; 
import java.util.Scanner; 

class off_to_ascii_points 
{ 
    private static Scanner scanner = new Scanner(System.in);  
    private static Pattern fat_word_pattern = Pattern.compile("\\s*\\S*\\s*"); 
    private static Pattern line = Pattern.compile(".*\\n", Pattern.MULTILINE); 

    public static void main(String[] args) 
    { 
     try 
     { 
      scanner.useLocale(java.util.Locale.US); 

        /* skip to the number of points */ 
      scanner.skip(fat_word_pattern); 

      int n_points = scanner.nextInt(); 

        /* skip the rest of the 2. line */ 
      scanner.skip(fat_word_pattern); scanner.skip(fat_word_pattern); 

      for (int i = 0; i < n_points; ++i) 
      { 
        System.out.print(scanner.next(line)); 
         /* 
         Here my mistake is. 
         next() reads only until the delimiter, 
         which is by default any white-space-sequence. 
         That is next() does not read till the end of the line 
         what i wanted. 

         Changing "next(line)" to "nextLine()" solves the problem. 
         Also, setting the delimiter to line_separator 
         right before the loop solves the problem too. 
         */ 
      } 

     } 
     catch(java.lang.Exception e) 
     { 
      System.err.println("exception"); 
      e.printStackTrace(); 
     } 
    } 
} 

시작은 다음

OFF 
4999996 10000000 0 
-28.6663 -11.3788 -58.8252 
-28.5917 -11.329 -58.8287 
-28.5103 -11.4786 -58.8651 
-28.8888 -11.7784 -58.9071 
-29.6105 -11.2297 -58.6101 
-29.1189 -11.429 -58.7828 
-29.4967 -11.7289 -58.787 
-29.1581 -11.8285 -58.8766 
-30.0735 -11.6798 -58.5941 
-29.9395 -11.2302 -58.4986 
-29.7318 -11.5794 -58.6753 
-29.0862 -11.1293 -58.7048 
-30.2359 -11.6801 -58.5331 
-30.2021 -11.3805 -58.4527 
-30.3594 -11.3808 -58.3798 

제가 첫번째 점의 좌표를 포함하는 라인의 수는 번호 4,999,996에 이동. 이 줄은 출력에 쓰려고합니다.

답변

4

나는 예상대로 코드가 작동하지 않는 이유는

private static Pattern line = Pattern.compile(".*"); 

scanner.useDelimiter("[\\r\\n]+"); // Insert right before the for-loop 

System.out.println(scanner.next(line)); //Replace print with println 

을 사용하는 것이 좋습니다.

javadoc의 상태는 :

스캐너는 기본적으로 공백 일치하는 구분자 패턴을 사용하여 토큰 에 입력을 나누기.

즉, Scanner's.next * 메소드 중 하나를 호출하면 스캐너는 다음 구분 기호가 발견 될 때까지 지정된 입력을 읽습니다.

그래서 scanner.next(line)에 대한 첫 번째 호출은 다음 줄을

-28.6663 -11.3788 -58.8252 

를 읽고 그리고 -28.6663 후 공간 중지 시작합니다. 그런 다음 토큰 (-28.6663)이 분명히 일치하지 않는 제공된 패턴 (. * \ n) (-28.6663)과 일치하는지 확인합니다. 그래서 이유가 있습니다.

+0

코드가 실패한 이유를 설명하는 섹션 추가 – jitter

0

Pattern을 여러 줄 모드로 전환해야합니다.

이 스캐너 사용 클래스와 어떻게 클래스 작품과 관련이있다 :

line = Pattern.compile("^.*$", Pattern.MULTILINE); 
System.out.println(scanner.next(line)); 
+0

MULTILINE도 작동하지 않습니다. 일치하는 문자열에 new_line 문자를 포함 시키려면 $ 문자로 충분하지 않습니다. – libeako

0

기본적으로 스캐너는 공백을 구분 기호로 사용합니다. 첫 번째 건너 뛴 후에 줄을 읽기 전에 구분 기호를 새 줄로 변경해야합니다. 변경해야하는 코드는 for 루프 앞에 다음 행을 삽입하는 것입니다.

scanner.useDelimiter (Pattern.compile (System.getProperty ("line.separator"))));

다음과 같은 라인 패턴 변수 갱신 :

개인 정적 패턴 라인 =는 Pattern.compile (". *"를 패턴.다중 라인);

+0

"line.separator"속성은 신뢰할 수 없습니다. 주어진 파일은 임의의 스타일의 줄 분리 기호를 사용할 수도 있고 심지어 두 가지 스타일을 혼합하여 사용할 수도 있습니다. 스캐너의 hasNextLine() 및 nextLine() 메서드는이를 고려합니다. –

1

표준 출력으로 만 파일을 인쇄하려면 왜 regexps를 사용 하시겠습니까? 첫 번째 두 줄을 건너 뛰기를 원한다는 사실을 알고 있다면 그것을 수행하는 더 간단한 방법이 있습니다.

import java.util.Scanner; 
import java.io.File; 

public class TestClass { 
    public static void main(String[] args) throws Exception { 
     Scanner in=new Scanner(new File("test.txt")); 
     in.useDelimiter("\n"); // Or whatever line delimiter is appropriate 
     in.next(); in.next(); // Skip first two lines 
     while(in.hasNext()) 
      System.out.println(in.next()); 
    } 
} 
+0

줄 수를 읽어야합니다. 2. 라인의 첫 번째 단어입니다. – libeako

0

도움을 주신 모든 분들께 감사드립니다.

지금 내가 내 실수 이해 : 스캐너 클래스의 모든 nextT() 메소드는 우선 구분 기호 패턴을 건너 뛰는 것을,

API 설명서 상태를, 다음은 T 값을 읽으려고합니다. 그러나 각 next ...() 메소드는 구분 기호가 처음 나타날 때까지만 읽는다는 것을 잊어 버립니다!