English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
기본 문자"\\s"공백과 일치합니다.+공백이 한 번이나 여러 번 나타날 수 있음을 나타냅니다. 따라서 정규 표현식 \\ S +모든 공백 문자(단일이나 여러 개)와 일치합니다. 따라서 여러 개의 공백을 단일 공백으로 대체합니다.
입력된 문자열을 위에서 설명한 정규 표현식과 일치시키고, 그 결과를 단일 공백 문자 ""로 대체합니다.
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("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String regex = "\\s+"; //정규 표현식 컴파일 Pattern pattern = Pattern.compile(regex); //매칭기검색기 객체 검색 Matcher matcher = pattern.matcher(input); //所有空格字符으로 단일 공백 대체 String result = matcher.replaceAll(" "); System.out.print("Text after removing unwanted spaces: \n"+result); } }
출력 결과
Enter a String hello this is a sample text with irregular spaces Text after removing unwanted spaces: hello this is a sample text with irregular spaces
import java.util.Scanner; public class Test { public static void main(String args[]) { //用户에서 문자열 읽기 System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); //正则表达式以匹配空格 String regex = "\\s+"; //单个空格替换模式 String result = input.replaceAll(regex, " "); System.out.print("Text after removing unwanted spaces: \n"+result); } }
출력 결과
Enter a String hello this is a sample text with irregular spaces Text after removing unwanted spaces: hello this is a sample text with irregular spaces