2011-04-05 4 views
0

자바에서 정규식을 관리하는 방법은 무엇입니까?자바에서 정규식 관리

예 정규식 주제를 검색했지만 자바에서 이상하다고 생각합니다. 내가하고 싶은 무엇

내가 한 위

Pattern p = Pattern.compile("(.+?)\\<.*?\\>?"); 

하지 않았다 [email protected]로 < 사이의 문자열을> 좀하고 싶습니다, 정규식

My team <[email protected]> 

입니다 작업.

답변

3

어쩌면 이런가?

Pattern p = Pattern.compile("(.+?)<(.*?)>"); 
    Matcher matcher = p.matcher("Foo bar <[email protected]>"); 
    if (matcher.matches()) { 
     System.out.println(matcher.group(2)); 
    } 
+0

예외 : java.util.regex.Matcher.group (알 수없는 소스) – smlnl

+0

이상한 찾았 일치에 작동하지 않습니다 내 컴퓨터에 자바 6. 편집 : 내부 jUnit4 테스트, 그 :) –

+0

정말요? 이 패턴과 매처를 반복하면 어떻게 될까요? 그것은 어떤 situtation을 변경합니까 ?? – smlnl

4

실제로 문자열을 처리하려면 Matcher 객체에서 find() 메소드를 호출해야합니다. 페트리 펠리 넨 (Petri Pellinen)이 말한대로 적절한 그룹화를 확인해야합니다.

다음 코드보십시오 :

String str = "My team <[email protected]> My team <[email protected]> \n " + 
    "My team <[email protected]> My team <[email protected]> " + 
    "My team <[email protected]> My team <[email protected]>"; 

Pattern p = Pattern.compile("\\<(.*?)\\>"); 
Matcher m = p.matcher(str); 

while(m.find()){ 
    System.out.println(m.group(1)); 
} 

및 그룹이 가져온 확인합니다.

결과는 다음과 같습니다

[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 

환호!

3

표준 형식 이메일 주소 (RFC 822)를 다루고있는 것으로 보인 이후 JavaMail API을 사용하는 것이 좋습니다. 정규 표현식을 사용하면 일부 경우를 놓칠 수 있지만 스펙 내 모든 것을 처리하도록 설계되었습니다. 당신이 원하는에 대한 코드는 간단한 너무 : 스레드 "주요"java.lang.IllegalStateException에서

String input = "My team <[email protected]>"; 
String email = new InternetAddress(input).getAddress();