정규식 "\\s"는 문자열의 공백과 일치합니다. replaceAll() 메서드는 문자열을 받아들이고 정규식은 일치하는 문자를 주어진 문자열로 바꿉니다. 입력 문자열에서 모든 공백을 제거하려면 replaceAll()을 호출합니다. 위에서 언급한 정규식과 빈 문자열을 입력으로 우회하는 방법입니다.
예시 1
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
마찬가지로 appendReplacement() 메소드는 문자열 버퍼와 대체 문자열을 받아들이고, 주어진 대체 문자열과 일치하는 문자를 추가하고 문자열 버퍼에 추가합니다.
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);
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
//Creating an empty string buffer
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
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