developer tip

자바 정규식 일치 수

optionbox 2020. 9. 16. 07:36
반응형

자바 정규식 일치 수


파일이 있고 파일에 다음이 포함되어 있다고 가정 해 보겠습니다.

HelloxxxHelloxxxHello

'Hello'를 찾기 위해 패턴을 컴파일합니다.

Pattern pattern = Pattern.compile("Hello");

그런 다음 inputstream을 사용하여 파일을 읽고 정규식이 될 수 있도록 String으로 변환합니다.

matcher가 파일에서 일치하는 항목을 찾으면이를 표시하지만 찾은 일치 항목 수를 알려주지 않습니다. 단순히 문자열 내에서 일치하는 것을 찾았습니다.

따라서 문자열이 비교적 짧고 사용중인 버퍼가 200 바이트이므로 세 개의 일치 항목을 찾아야합니다. 그러나 그것은 단순히 일치라고 말하고 얼마나 많은 일치가 있었는지에 대한 카운트를 제공하지 않습니다.

문자열 내에서 발생한 일치 수를 계산하는 가장 쉬운 방법은 무엇입니까? 다양한 for 루프를 시도하고 matcher.groupCount ()를 사용했지만 아무데도 빨리 나오지 않습니다.


matcher.find()모든 일치 항목을 찾지 않고 다음 일치 항목 찾습니다 .

다음을 수행해야합니다.

int count = 0;
while (matcher.find())
    count++;

Btw matcher.groupCount()는 완전히 다른 것입니다.

완전한 예 :

import java.util.regex.*;

class Test {
    public static void main(String[] args) {
        String hello = "HelloxxxHelloxxxHello";
        Pattern pattern = Pattern.compile("Hello");
        Matcher matcher = pattern.matcher(hello);

        int count = 0;
        while (matcher.find())
            count++;

        System.out.println(count);    // prints 3
    }
}

겹치는 일치 처리

위의 스 니펫 aa에서 aaaa일치를 계산할 때 2 를 제공합니다 .

aaaa
aa
  aa

3 개 일치를 얻으려면, 즉이 동작 :

aaaa
aa
 aa
  aa

<start of last match> + 1다음과 같이 색인에서 일치하는 항목을 검색해야 합니다.

String hello = "aaaa";
Pattern pattern = Pattern.compile("aa");
Matcher matcher = pattern.matcher(hello);

int count = 0;
int i = 0;
while (matcher.find(i)) {
    count++;
    i = matcher.start() + 1;
}

System.out.println(count);    // prints 3

이것은 겹칠 수있는 일치에 대해 작동합니다.

public static void main(String[] args) {
    String input = "aaaaaaaa";
    String regex = "aa";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input);
    int from = 0;
    int count = 0;
    while(matcher.find(from)) {
        count++;
        from = matcher.start() + 1;
    }
    System.out.println(count);
}

Java 8 스트림을 사용하고 while루프에 알레르기가있는 경우 다음을 시도해 볼 수 있습니다.

public static int countPattern(String references, Pattern referencePattern) {
    Matcher matcher = referencePattern.matcher(references);
    return Stream.iterate(0, i -> i + 1)
            .filter(i -> !matcher.find())
            .findFirst()
            .get();
}

면책 조항 : 이것은 비 연속 매치에서만 작동합니다.

예:

public static void main(String[] args) throws ParseException {
    Pattern referencePattern = Pattern.compile("PASSENGER:\\d+");
    System.out.println(countPattern("[ \"PASSENGER:1\", \"PASSENGER:2\", \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
    System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
    System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\", \"PASSENGER:1\" ]", referencePattern));
    System.out.println(countPattern("[  ]", referencePattern));
}

다음과 같이 출력됩니다.

2
0
1
0

이것은 스트림과의 분리 된 일치를위한 솔루션입니다.

public static int countPattern(String references, Pattern referencePattern) {
    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
            new Iterator<Integer>() {
                Matcher matcher = referencePattern.matcher(references);
                int from = 0;

                @Override
                public boolean hasNext() {
                    return matcher.find(from);
                }

                @Override
                public Integer next() {
                    from = matcher.start() + 1;
                    return 1;
                }
            },
            Spliterator.IMMUTABLE), false).reduce(0, (a, c) -> a + c);
}

Use the below code to find the count of number of matches that the regex finds in your input

        Pattern p = Pattern.compile(regex, Pattern.MULTILINE | Pattern.DOTALL);// "regex" here indicates your predefined regex.
        Matcher m = p.matcher(pattern); // "pattern" indicates your string to match the pattern against with
        boolean b = m.matches();
        if(b)
        count++;
        while (m.find())
        count++;

This is a generalized code not specific one though, tailor it to suit your need

Please feel free to correct me if there is any mistake.

참고URL : https://stackoverflow.com/questions/7378451/java-regex-match-count

반응형