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));
}
출처
2012-07-06 19:33:11
oxc
Java의 정규식 구현을 사용하고 있습니까? –