如何使用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[]) {
//从用户读取字符串
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
例子2
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
热门推荐
10 广西考试祝福语结婚简短
11 猪年祝福语简短小孩
12 元旦祝福语送长辈简短
13 恭喜二宝祝福语简短
14 祝福语暖心话简短
15 国庆中秋祝福语简短兄弟
16 朋友订婚的祝福语简短
17 送弟弟中秋祝福语简短
18 爱生日祝福语简短独特