정규식 "\\s"는 문자열 내의 모든 공백 문자와 일치합니다. Java의 replaceAll() 메서드는 문자열과 정규식을 인자로 받아, 정규식과 일치하는 문자들을 지정된 문자열로 대체해 줍니다. 따라서 입력 문자열에서 모든 공백을 제거하려면 replaceAll() 메서드를 호출하면서 위 정규식과 빈 문자열("")을 인자로 전달하면 됩니다.
예제 1: replaceAll() 메서드 활용
가장 간단하고 널리 사용되는 방법입니다. replaceAll()에 정규식 "\\s"와 빈 문자열을 전달하여 공백을 한 번에 제거할 수 있습니다.
public class RemovingWhiteSpaces {
public static void main( String args[] ) {
String input = "Hi welcome to tutorialspoint";
String regex = "\s";
String result = input.replaceAll(regex, "");
System.out.println("Result: "+result);
}
}실행 결과
Result: Hiwelcometotutorialspoint
예제 2: Matcher의 appendReplacement() 메서드 활용
appendReplacement() 메서드는 StringBuffer와 대체 문자열을 인자로 받아, 정규식과 일치하는 부분을 대체 문자열로 바꾼 후 StringBuffer에 추가합니다. 이 방식은 매칭 과정을 세밀하게 제어해야 할 때 유용하며, 사용자 입력을 받아 처리하는 예제입니다.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RemovingWhiteSpaces {
public static void main( String args[] ) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string: ");
String input = sc.nextLine();
String regex = "\s";
String constants = "";
System.out.println("Input string: \n"+input);
// 패턴 객체 생성
Pattern pattern = Pattern.compile(regex);
// 컴파일된 패턴을 문자열과 매칭
Matcher matcher = pattern.matcher(input);
// 비어 있는 StringBuffer 생성
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
constants = constants+matcher.group();
matcher.appendReplacement(sb, "");
}
matcher.appendTail(sb);
System.out.println("Result: \n"+ sb.toString()+constants );
}
}실행 결과
Enter input string: this is a sample text with white spaces Input string: this is a sample text with white spaces Result: thisisasampletextwithwhitespaces
예제 3: split() 메서드 활용
정규식 외에도 split() 메서드를 사용하면 문자열을 공백 기준으로 분리한 뒤 다시 하나로 합치는 방식으로 공백을 제거할 수 있습니다.
public class Just {
public static void main(String args[]) {
String input = "This is a sample text with spaces";
String str[] = input.split(" ");
String result = "";
for(int i=0; i<str.length; i++) {
result = result+str[i];
}
System.out.println("Result: "+result);
}
}실행 결과
Result: Thisisasampletextwithspaces
마무리
지금까지 Java에서 정규식을 활용해 문자열의 공백을 제거하는 다양한 방법을 살펴보았습니다. 일반적으로는 replaceAll("\\s", "") 한 줄로 해결하는 것이 가장 효율적이며, 탭이나 줄바꿈 등 모든 종류의 공백 문자까지 함께 제거됩니다. 상황에 맞는 방법을 선택하여 깔끔한 문자열 처리를 구현해 보세요.