2016-06-29 3 views
0

많은 파일이 있습니다. "msql"로 시작하는 특정 줄을 찾고 싶습니다.자바 정규식 패턴 일치 시작을

나는 많은 정규식 조합을 시도했지만 어떤 아이디어도 얻지 못했습니다.

Pattern pattern = Pattern.compile("^msql"); 
Matcher matcher = pattern.matcher(s); 

또는

s.matches("^(msql).*$") or s.matches("^msql") 

는 라인 "은 mSQL"로 시작을 찾기위한 올바른 정규식을 제안 해주십시오.

편집 : -

내가 파일 데이터를 다음과 같이 가지고있다 -

eventlogger 0 0 1 1 1 10 
expireserv 0 0 1 1 1 10 " 
partEOLserv 0 0 1 1 1 10 
msqlpdmm81dd 0 0 25 25 25 

내 코드입니다.

String s = br.readLine(); 
while (s != null) { 
    //Pattern pattern = Pattern.compile("^msql"); 
    //("^(msql).*$") 
    //Matcher matcher = pattern.matcher(s); 
    System.out.println(s); 

    if (s.startsWith("msql")) { 
     System.out.println(s); 

    } 

    s = br.readLine(); 
} 

아직 행을 찾을 수 없습니다.

+4

'String.startsWith() '를 사용하지 않는 이유 –

+0

@MichaelMarkidis : -이 방법을 시도했지만 성공하지 못했습니다. 편집 된 질문을보십시오. –

+3

시작 부분에 여분의 공백이 포함되어있을 수 있습니다. 's.matches ("^ \\ s * msql. * $")' –

답변

0

첫 번째 줄만 읽고 있으므로 일치하는 내용이 없습니다.

public static void main(String[] args) throws Exception { 
     File f = new File("example.txt"); 
     BufferedReader br = new BufferedReader(new FileReader(f)); 
     String temp = null; 
     while ((temp=br.readLine())!=null) { 
      if (temp.startsWith("msql")){ 
       System.out.println("Match found: "+temp); 
      } 
     } 
    } 

출력

Match found: msqlpdmm81dd 0 0 25 25 25

0

콘텐츠 매칭 정규식이 정확하다. 왜 당신이 문제를 겪고 있는지 나는 모른다. 나는 당신의 프로그램을 시험해 보았고 효과가있다.
아래 정규식 코드를 추가합니다.

BufferedReader br = new BufferedReader(new FileReader("<filepath\\filename.extension>")); 
     String s; 
     while ((s = br.readLine()) != null) { 
      if (s.matches("^(msql).*$")){ 
       System.out.println(s); 
      } else { 
       System.out.println("didnt matched"); 
      } 
     } 

는 또한 이것은 또한 잘 작동한다

if (s.startsWith("msql")) 

사용 상태를 확인할 수 있습니다.
로컬에 텍스트 파일을 만들고 데이터를 저장했습니다. 그리고 나는 다음과 같은 결과를 얻는다.

didnt matched 
didnt matched 
didnt matched 
msqlpdmm81dd 0 0 25 25 25 

나는 이것이 효과가 있다고 생각한다.