\s* 表示若干个空格(可以是0个)。
\s+ 表示一个或多个空格
public class Test {
public static void main(String[] args) {
String str = " kk kkk klaf fsaff fsge tg sagh ger fsaga ";
//测试的字符串
String regex = "\\s+";
//表示一个或多个空格的<a href="https://www.baidu.com/s?wd=%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1Y1uHRLnAnsPHf3PvfLnW040AP8IA3qPjfsn1bkrjKxmLKz0ZNzUjdCIZwsrBtEXh9GuA7EQhF9pywdQhPEUiqkIyN1IA-EUBtkPHDkn1bYPHDYnHnYnj0vPH0s" target="_blank" class="baidu-highlight">正则表达式</a>
str = str.trim();
//去掉字符串开头和结尾的空格
String str1 = str.replaceAll(regex,"");
//去掉所有的空格
String str2 = str.replaceAll(regex," ");
//把一个或多个空格替换成一个空格
System.out.println(str);
System.out.println(str1);
System.out.println(str2);
}
}
输出结果: kk kkk klaf fsaff fsge tg sagh ger fsaga kkkkkklaffsafffsgetgsaghgerfsaga kk kkk klaf fsaff fsge tg sagh ger fsaga