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

자바 정규식으로 공백과 구두점 기준 문자열 분할하기

정규식 패턴으로 구두점과 공백 찾기

정규식 문자 클래스 [!._,'@? ]는 마침표(.), 밑줄(_), 쉼표(,), 작은따옴표('), @, 물음표(?), 그리고 공백 문자를 모두 매칭합니다. 여기에 공백을 의미하는 \s를 함께 사용하면 탭이나 줄바꿈을 포함한 모든 종류의 공백까지 처리할 수 있습니다.

예제 1: Pattern과 Matcher로 매칭 개수 세기

java.util.regex 패키지의 PatternMatcher 클래스를 사용하면 입력 문자열에서 해당 패턴이 몇 번 나타나는지 손쉽게 확인할 수 있습니다.

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

public class Test {
   public static void main(String args[]) {
      String input = "This is!a.sample\"text,with punctuation!marks";
      Pattern p = Pattern.compile("[!._,'@?//s]");
      Matcher m = p.matcher(input);
      int count = 0;
      while(m.find()) {
         count++;
      }
      System.out.println("Number of matches: "+count);
   }
}

실행 결과:

Number of matches: 8

while 루프 안에서 m.find()는 더 이상 매칭되는 구간이 없을 때까지 반복 호출되며, 일치가 발생할 때마다 카운트가 1씩 증가합니다.

split() 메서드로 문자열 분할하기

String 클래스의 split() 메서드는 정규식을 인자로 받아, 두 매칭 지점 사이의 문자열을 하나의 토큰(단어)으로 간주하고 현재 문자열을 토큰 배열로 분할합니다.

예를 들어 구분자로 단일 공백(" ")을 전달하면, 두 공백 사이의 단어를 하나의 토큰으로 취급하여 공백으로 구분된 단어들의 배열을 반환합니다.

따라서 모든 공백과 구두점을 기준으로 문자열을 나누려면, 앞서 살펴본 정규식을 매개변수로 전달하며 split() 메서드를 호출하면 됩니다.

예제 2: StringTokenizer 활용하기

java.util.StringTokenizer 클래스를 사용하면 구분자 문자열을 기준으로 토큰을 간편하게 추출할 수 있습니다. 아래 예제는 사용자로부터 문자열을 입력받아 구두점과 공백을 기준으로 단어를 한 줄씩 출력합니다.

import java.util.Scanner;
import java.util.StringTokenizer;

public class RegExample {
   public static void main(String args[]) {
      String regex = "[!._,'@? ]";
      System.out.println("Enter a string: ");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      StringTokenizer str = new StringTokenizer(input, regex);
      while(str.hasMoreTokens()) {
         System.out.println(str.nextToken());
      }
   }
}

실행 결과:

Enter a string:
This is!a.sample text,with punctuation!marks@and_spaces
This
is
a
sample
text
with
punctuation
marks
and
spaces

정리

정규식 문자 클래스와 split() 메서드 또는 StringTokenizer를 조합하면 공백과 여러 종류의 구두점이 섞인 문자열도 손쉽게 분할할 수 있습니다. 정규식을 온전히 지원하는 split()은 복잡한 패턴 처리에 적합하고, StringTokenizer는 단순한 구분 작업에 가볍게 활용할 수 있습니다.