如何使用 Java 正则表达式用单个空格替换字符串中的多个空格?
元字符 “\s” 匹配空格,+ 表示空格出现一次或多次,因此正则表达式 \S+ 会匹配所有空格字符(单个或多个)。因此,用单个空格替换多个空格。
使用上述正则表达式匹配输入字符串,并将结果替换为单个空格“ ”。
示例 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "\s+";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
//Replacing all space characters with single space
String result = matcher.replaceAll(" ");
System.out.print("Text after removing unwanted spaces: \n"+result);
}
}Maruthi Krishna
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[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//Regular expression to match space(s)
String regex = "\s+";
//Replacing the pattern with single space
String result = input.replaceAll(regex, " ");
System.out.print("Text after removing unwanted spaces: \n"+result);
}
}Maruthi Krishna
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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP