English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
부분 표현식/기본 문자 " \ s"는 공백과 동일합니다.
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { String regex = "\\s"; String input = "您好,欢迎来到w"3codebox!"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(input); int count = 0; while(m.find()) {}} count++; } System.out.println("matches의 수: "+count); } }
출력 결과
matches의 수: 7
아래의 예제는 문자열을 읽어들이고 그들 간의 모든 추가 공백을 제거합니다.
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { 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