program story

캡처 그룹으로 Java Regex 바꾸기

inputbox 2020. 11. 2. 07:56
반응형

캡처 그룹으로 Java Regex 바꾸기


정규 표현식을 캡처 그룹의 수정 된 내용으로 대체하는 방법이 있습니까?

예:

Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher(text);
resultString = regexMatcher.replaceAll("$1"); // *3 ??

그리고 모든 발생을 $ 1에 3을 곱한 값으로 바꾸고 싶습니다.

편집하다:

뭔가 잘못된 것 같습니다 :(

내가 사용한다면

Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher("12 54 1 65");
try {
    String resultString = regexMatcher.replaceAll(regexMatcher.group(1));
} catch (Exception e) {
    e.printStackTrace();
}

IllegalStateException이 발생합니다. 일치하는 항목이 없습니다.

그러나

Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher("12 54 1 65");
try {
    String resultString = regexMatcher.replaceAll("$1");
} catch (Exception e) {
    e.printStackTrace();
}

잘 작동하지만 $ 1을 변경할 수 없습니다.

편집하다:

이제 작동 중입니다. :)


어때 :

if (regexMatcher.find()) {
    resultString = regexMatcher.replaceAll(
            String.valueOf(3 * Integer.parseInt(regexMatcher.group(1))));
}

첫 번째 일치 항목을 얻으려면 #find(). 그런 #group(1)다음를 사용 하여이 첫 번째 일치 항목을 참조하고 모든 일치 항목을 첫 번째 maches 값에 3을 곱한 값으로 바꿀 수 있습니다.

그리고 각 일치 항목을 해당 일치 값에 3을 곱한 값으로 바꾸려는 경우

    Pattern p = Pattern.compile("(\\d{1,2})");
    Matcher m = p.matcher("12 54 1 65");
    StringBuffer s = new StringBuffer();
    while (m.find())
        m.appendReplacement(s, String.valueOf(3 * Integer.parseInt(m.group(1))));
    System.out.println(s.toString());

Matcher문서 와 더 많은 내용을 자세히 다루는 의 문서 를 살펴볼 수 있습니다 .


얼의 대답은 당신에게 해결책을 제공하지만 나는 당신의 IllegalStateException. group(1)먼저 일치 작업 (예 :)을 호출 하지 않고 호출합니다 find(). 일치하는 작업 $1이므로 사용하는 경우에는 필요하지 않습니다 replaceAll().


출처 : java-implementation-of-rubys-gsub

용법:

// Rewrite an ancient unit of length in SI units.
String result = new Rewriter("([0-9]+(\\.[0-9]+)?)[- ]?(inch(es)?)") {
    public String replacement() {
        float inches = Float.parseFloat(group(1));
        return Float.toString(2.54f * inches) + " cm";
    }
}.rewrite("a 17 inch display");
System.out.println(result);

// The "Searching and Replacing with Non-Constant Values Using a
// Regular Expression" example from the Java Almanac.
result = new Rewriter("([a-zA-Z]+[0-9]+)") {
    public String replacement() {
        return group(1).toUpperCase();
    }
}.rewrite("ab12 cd efg34");
System.out.println(result);

구현 (재 설계) :

import static java.lang.String.format;

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

public abstract class Rewriter {
    private Pattern pattern;
    private Matcher matcher;

    public Rewriter(String regularExpression) {
        this.pattern = Pattern.compile(regularExpression);
    }

    public String group(int i) {
        return matcher.group(i);
    }

    public abstract String replacement() throws Exception;

    public String rewrite(CharSequence original) {
        return rewrite(original, new StringBuffer(original.length())).toString();
    }

    public StringBuffer rewrite(CharSequence original, StringBuffer destination) {
        try {
            this.matcher = pattern.matcher(original);
            while (matcher.find()) {
                matcher.appendReplacement(destination, "");
                destination.append(replacement());
            }
            matcher.appendTail(destination);
            return destination;
        } catch (Exception e) {
            throw new RuntimeException("Cannot rewrite " + toString(), e);
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(pattern.pattern());
        for (int i = 0; i <= matcher.groupCount(); i++)
            sb.append(format("\n\t(%s) - %s", i, group(i)));
        return sb.toString();
    }
}

Java 9는 Matcher.replaceAll()대체 기능을 허용하는를 제공 합니다.

resultString = regexMatcher.replaceAll(
        m -> String.valueOf(Integer.parseInt(m.group()) * 3));

참고 URL : https://stackoverflow.com/questions/1277157/java-regex-replace-with-capturing-group

반응형