2014-04-22 12 views
0

특정 패턴과 일치하는 문자열에서 추출 된 값을 반환하고 싶습니다. FOT 예를 들면 : 당신이 문자열 Matcher 개체를 비교하는 문자열의 = "[email protected]"패턴이있는 정규식을 사용하여 문자열에서 값 추출

import java.util.*; 
import java.util.regex.Pattern; 
import java.util.regex.Matcher; 

class regexprac{ 
    public static void main(String args[]){ 
     String x = "[email protected]"; 
     String existingdomain = "hotmail"; 

     Pattern emailPattern = Pattern.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"); 

     if(existingdomain.equals(emailPattern.matcher(x))){ 
      System.out.println("Found it"); 
     }else{ 
      System.out.println("Not found it"); 
     } 


    } 
} 
+0

이 대답을받지 않습니다. emailPattern이 hotmail을 이메일로 추출하길 원합니다. – user3229011

+0

''@ "'다음에 텍스트를 가져 오려고 했습니까? –

+0

항상 핫메일이 될 것입니까? – smistry

답변

0
if(existingdomain.equals(emailPattern.matcher(x))){ 

에서 "핫메일"을 추출 할. 그것은 결코 사실로 평가되지 않을 것입니다. Pattern.matcher()을 참조하십시오.

matcher에서 find()group() 메서드를 호출하고 반환 값을 문자열과 비교해야합니다.


업데이트

String x = "[email protected]"; 
String y = "[email protected]"; 
Pattern p = Pattern.compile("[email protected]([^.]+)\\."); 
Matcher m = p.matcher(x); 
if (m.find()) { 
    System.out.println("found: " + m.group(1)); 
} 
m = p.matcher(y); 
if (m.find()) { 
    System.out.println("found: " + m.group(1)); 
} 

출력 :

 
found: hotmail 
found: outlook 
+0

find() 메서드는 값을 반환합니다 ?? – user3229011

+0

게다가 "@"와 첫 번째 "사이에 물건을 원합니다." @ – user3229011

+0

@ user3229011 뒤에서 발생합니다.'String' 클래스는 당신을 도울 수있는 몇 가지 메소드를 가지고 있습니다 : ['String # substring'] (http://docs.oracle.com/javase/8/docs/api/java/lang/String. html # substring-int-int-) 및 ['String # indexOf'] (http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#indexOf-int-)를 참조하십시오. –

0

이 시도 :

import java.util.*; 
import java.util.regex.Pattern; 
import java.util.regex.Matcher; 

class regexprac{ 
    public static void main(String args[]){ 
     String x = "[email protected]"; 
     String existingdomain = "hotmail"; 

     Pattern emailPattern = Pattern.compile("(^[A-Z0-9._%+-]+)(@)([A-Z0-9.-]+)(\\.)([A-Z]{2,6}$)", Pattern.CASE_INSENSITIVE); 
     Matcher matcher = emailPattern.matcher(x); 
     if(matcher.find())){ 
      System.out.println("Found it"); 
      String provider = matcher.group(2); 
     }else{ 
      System.out.println("Not found it"); 
     } 
    } 
} 
+0

@와 첫 번째 사이의 패턴을 원합니다. " – user3229011

+0

matcher.find() 작동 – user3229011

+0

하지만 우리가 원하는 값을 추출하기 위해 그룹화 할 수 있습니다 – user3229011

관련 문제