2012-07-06 4 views
1

이전에 동일한 문자열에서 정의 된 변수 템플릿에 의해 식별되는 문자열에 포함 된 값을 정규식 추출 할 수 있습니까? 또는 Java에서 더 잘 처리됩니까?문자열에서 n 값을 추출하는 정규 표현식

예 : "2012 Ferrari [F12] - 타조 가죽 인테리어 [F12 # OL] - 캔디 레드 메탈릭 [F12 # 3]"변수 템플릿은 대괄호가있는 첫 번째 문자열입니다. [F12], 원하는 변수가 해당 템플릿의 후속 인스턴스 내에서 발견됩니다. 'OL'과 '3'.

+0

Java의 정규식 구현을 사용하고 있습니까? –

답변

0

Java를 언급 한 이후로 Java 구현 인 Pattern을 사용하고 있다고 가정합니다.

자바의 패턴 때문에 이전 캡처 그룹 일치 같은 값과 일치하는 데 사용할 수있는 다시 참조을,라는 지원합니다.

불행히도 단일 캡처 그룹에서 여러 값을 추출 할 수 없기 때문에 단일 패턴으로이를 수행하려면 일치시킬 템플릿 수를 하드 코딩해야합니다.

하나 개의 변수 들어, 다음과 같이 수 :

\[(.*?)\].*?\[\1#(.*?)\] 
    ^^^^^   ^^^^^ variable 
template  ^^ back reference to whatever template matched 

당신은 더 많은 옵션 일치를 추가 할 수 있습니다 같은 옵션 비 캡처 그룹에 그들을 배치 기준 :

\[(.*?)\].*?\[\1#(.*?)\](?:.*?\[\1#(.*?)\])?(?:.*?\[\1#(.*?)\])? 
         ^optional group ^another one 

이 일치 것 세 변수로 :

String s = "2012 Ferrari [F12] - Ostrich Leather interior [F12#OL] - Candy Red Metallic [F12#3]"; 
    String pattern = "\\[(.*?)\\].*?\\[\\1#(.*?)\\](?:.*?\\[\\1#(.*?)\\])?(?:.*?\\[\\1#(.*?)\\])?"; 
    Matcher matcher = Pattern.compile(pattern).matcher(s); 
    if (matcher.find()) { 
     for (int i = 1; i <= matcher.groupCount(); i++) { 
      System.out.println(matcher.group(i)); 
     } 
    } 

    // prints F12, OL, 3, null 

변수 개수와 일치해야하는 경우 그럼, 첫 번째 단계에서 템플릿을 추출한 다음 두 번째 패턴에 포함시켜야합니다.

// compile once and store in a static variable 
    Pattern templatePattern = Pattern.compile("\\[(.*?)\\]"); 

    String s = "2012 Ferrari [F12] - Ostrich Leather interior [F12#OL] - Candy Red Metallic [F12#3]"; 

    Matcher templateMatcher = templatePattern.matcher(s); 

    if (!templateMatcher.find()) { 
     return; 
    } 

    String template = templateMatcher.group(1); 
    Pattern variablePattern = Pattern.compile("\\[" + Pattern.quote(template) + "#(.*?)\\]"); 

    Matcher variableMatcher = variablePattern.matcher(s); 
    while (variableMatcher.find()) { 
     System.out.println(variableMatcher.group(1)); 
    } 
+0

나는 two-pass 방법이 필요합니다. 훌륭하게 작동합니다. 둘 다 주셔서 감사합니다! – MichaelS

관련 문제