정규식에서 메타 문자 "\s"는 공백 문자와 일치하며, "+"는 앞의 패턴이 한 번 이상 반복됨을 의미합니다. 따라서 정규식 "\s+"는 하나 또는 여러 개로 이어진 공백 문자를 모두 매칭할 수 있습니다.
즉, 문자열에 포함된 여러 개의 연속된 공백을 하나의 공백으로 바꾸려면, 입력 문자열을 "\s+" 정규식과 매칭한 뒤 그 결과를 단일 공백 " "으로 치환하면 됩니다.
예제 1 — Pattern과 Matcher 활용
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
public static void main(String args[]) {
// 사용자로부터 문자열 입력 받기
System.out.println("문자열을 입력하세요");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "\\s+";
// 정규식 컴파일
Pattern pattern = Pattern.compile(regex);
// Matcher 객체 생성
Matcher matcher = pattern.matcher(input);
// 모든 공백 문자를 단일 공백으로 치환
String result = matcher.replaceAll(" ");
System.out.print("불필요한 공백이 제거된 텍스트: \n"+result);
}
}실행 결과
문자열을 입력하세요 hello this is a sample text with irregular spaces 불필요한 공백이 제거된 텍스트: hello this is a sample text with irregular spaces
예제 2 — String.replaceAll() 활용
Pattern과 Matcher 클래스를 직접 사용하지 않고도, String 클래스가 제공하는 replaceAll() 메서드를 사용하면 더 간결하게 처리할 수 있습니다.
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
// 사용자로부터 문자열 입력 받기
System.out.println("문자열을 입력하세요");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// 공백(들)에 일치하는 정규식
String regex = "\\s+";
// 매칭된 패턴을 단일 공백으로 치환
String result = input.replaceAll(regex, " ");
System.out.print("불필요한 공백이 제거된 텍스트: \n"+result);
}
}실행 결과
문자열을 입력하세요 hello this is a sample text with irregular spaces 불필요한 공백이 제거된 텍스트: hello this is a sample text with irregular spaces
정리
정규식 "\s+"는 탭, 줄바꿈 등 모든 종류의 공백 문자를 포함하여 하나 이상 연속된 공백과 일치합니다. 따라서 replaceAll("\\s+", " ") 한 줄만으로도 문자열 내의 불규칙한 공백을 손쉽게 정리할 수 있습니다. 간단한 처리라면 예제 2처럼 String의 replaceAll() 메서드를 사용하는 것이 가장 효율적입니다.