English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java 정규 표현식(RegEx)을 사용하여 공백을 제거하는 방법

정규 표현식 "\\s"는 문자열의 공백과 일치합니다. 이replaceAll()메서드는 문자열을 받아서 주어진 문자열로 일치하는 문자를 대체합니다. 모든 공백을 제거하려면 위에 언급된 정규 표현식과 공백 문자열을 입력으로 사용하여 호출합니다.replaceAll()메서드.

예제1

public class RemovingWhiteSpaces {
   public static void main( String args[] ) {
      String input = "Hi welcome to w3codebox";
      String regex = "\\s";
      String result = input.replaceAll(regex, "");
      System.out.println("Result: "+result);
   }
}

출력 결과

결과: Hiwelcometow3codebox

예제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);
      //패턴 객체를 생성합니다
      Pattern pattern = Pattern.compile(regex);
      //문자열에서 이미 컴파일된 패턴을 매칭합니다
      Matcher matcher = pattern.matcher(input);
      //빈 문자열 버퍼를 생성합니다
      StringBuffer sb = new StringBuffer();
      while (matcher.find()) {
         constants = constants+matcher.group();
         matcher.appendReplacement(sb, "");
      }
      matcher.appendTail(sb);
      System.out.println("Result: 
"+ sb.toString()+constants );
   }
}

출력 결과

입력 문자열을 입력하세요:
this is a sample text with white spaces
입력 문자열:
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: 이것은 공백이 있는 샘플 텍스트입니다
추천해드립니다