元字符“ \\ 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