如何使用 Java 正则表达式将字符串中的多个空格替换为单个空格?
javaobject oriented programmingprogramming更新于 2024/5/11 9:16:17
元字符 “\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[]) {
//从用户读取字符串
System.out.println("输入字符串");
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 removed unwanted space: \n"+result);
}
}
输出
输入字符串 hello this is a sample text with irregular space Text after removed unwanted space: hello this is a sample text with irregular space
示例 2
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
//从用户那里读取字符串
System.out.println("输入字符串");
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);
}
}
输出
输入字符串 hello this is a sample text with irregular spaces Text after removing unwanted spaces: hello this is a sample text with irregular spaces
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

