Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java 정규식으로 일치하는 모든 문자열 목록 가져오기

Java에서는 정규식과 일치하는 모든 결과를 한 번에 반환해 주는 메서드를 기본적으로 제공하지 않습니다. 따라서 List 객체를 생성한 후, while 루프를 사용하여 매칭된 결과를 하나씩 리스트에 추가하는 방식으로 구현해야 합니다.

구현 방법

핵심 클래스는 다음 두 가지입니다.

  • Pattern: 정규식을 컴파일하여 패턴 객체를 생성합니다.
  • Matcher: 컴파일된 패턴을 대상 문자열에 적용하고, find() 메서드로 일치 항목을 순차적으로 탐색합니다.

matcher.find()가 더 이상 일치 항목을 찾지 못할 때까지 반복하면서 matcher.group()으로 현재 일치 문자열을 추출해 리스트에 저장하면 됩니다.

예제 코드

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ListOfMatches{
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "\d+";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      ArrayList list = new ArrayList();
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      while (matcher.find()) {
         list.add(matcher.group());
      }
      Iterator it = list.iterator();
      System.out.println("List of matches: ");
      while(it.hasNext()){
         System.out.println(it.next());
      }
   }
}

실행 결과

Enter input text:
sample 1432 text 53 with 363 numbers
List of matches:
1432
53
363

코드 설명

  1. 정규식 "\d+"는 하나 이상의 연속된 숫자를 의미합니다.
  2. Pattern.compile(regex)로 정규식을 컴파일하여 패턴 객체를 만듭니다.
  3. pattern.matcher(input)으로 입력 문자열에 대한 Matcher를 생성합니다.
  4. while(matcher.find()) 루프에서 일치하는 숫자 그룹을 group()으로 꺼내 ArrayList에 추가합니다.
  5. 마지막으로 Iterator를 사용해 리스트의 모든 요소를 출력합니다.

이처럼 Java 8 이전 방식에서는 위와 같은 절차가 필요하지만, Java 8 이상이라면 Matcher.results()와 스트림 API를 활용해 matcher.results().map(MatchResult::group).collect(Collectors.toList()) 형태로 더 간결하게 작성할 수도 있습니다.