2013-07-26 3 views
1

문자 내 라인이, 브라우저와 같은 간다 = 파이어 폭스정규식 처음 두 내가 자바 에 정규 표현을 사용하여 정규식 라인에서 두 단어를 추출하기 위해 노력하고있어

나는 아래의 코드

을 사용하고 있습니다
currentLine = currentLine.trim(); 
System.out.println("Current Line: "+ currentLine); 
Pattern p = Pattern.compile("(.*?)=(.*)"); 
Matcher m = p1.matcher(currentLine); 
if(m.find(1) && m.find(2)){ 
System.out.println("Key: "+m.group(1)+" Value: "+m.group(2)); 
} 

내가 얻을 출력은 키 : OWSER 값 : 파이어 폭스

BR 내 경우 오프 트리밍된다. PERL과 완벽하게 작동하는 이유는 그것이 내가 이런 식으로 행동하는 이유를 알 때까지 나에게 이상한 것 같습니다. 누군가 나를 도울 수 있습니까?

+0

'currentLine'의 값은 무엇입니까? 'System.out.println ("Current Line :"+ currentLine);에 인쇄 된 것. – acdcjunior

+0

@AdrianWragg (. *?)는 관련이 없으며, 욕심이 많지 않은 일치를 의미하므로 정규식 엔진을 처음부터 끝까지 멈추게합니다. 이 경우에는 꼭 필요한 것은 아니지만 약간 더 효율적일 수 있습니다. – sundar

답변

0

당신은 당신의 두 값을 얻기 위해 다음 String.substring=의 위치를 ​​찾기 위해 String.indexOf을 사용할 수 있습니다 : 당신이 m.find(2)를 호출 할 때

String currentLine = "BROWSER=Firefox"; 

int indexOfEq = currentLine.indexOf('='); 

String myKey = currentLine.substring(0, indexOfEq); 
String myVal = currentLine.substring(indexOfEq + 1); 

System.out.println(myKey + ":" + myVal); 
2

는 처음 두 문자를 제거합니다. From the JavaDocs (굵게 광산) : 다음

public boolean find(int start)

재설정이 정합하고 지정된 인덱스에서 시작하는 패턴 일치하는 입력 시퀀스의 다음 시퀀스를 찾기 위해 시도한다.

그래서, 단지 m.find() 사용

String currentLine = "BROWSER=FireFox"; 
System.out.println("Current Line: "+ currentLine); 
Pattern p = Pattern.compile("(.*?)=(.*)"); 
Matcher m = p.matcher(currentLine); 
if (m.find()) { 
    System.out.println("Key: "+m.group(1)+" Value: "+m.group(2)); 
} 

출력 :

Current Line: BROWSER=FireFox 
Key: BROWSER Value: FireFox 

See online demo here.

+0

완벽합니다. 올바른 진단과 해결책입니다. 이 찾기 양식에 대한 링크는 다음과 같습니다 (그러나 페이지의 다음 버전 일뿐입니다). http://docs.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html # 찾기 % 28int % 29 – sundar

관련 문제