如何使用 Java 正则表达式 (RegEx) 删除空格

javaobject oriented programmingprogramming更新于 2024/5/11 7:08:17

正则表达式"\s"与字符串中的空格匹配。replaceAll() 方法接受一个字符串,正则表达式将匹配的字符替换为给定的字符串。要从输入字符串中删除所有空格,请对其调用 replaceAll() 方法,绕过上述正则表达式和空字符串作为输入。

示例 1

public class RemovingWhiteSpaces {
   public static void main( String args[] ) {
      String input = "Hi welcome to tutorialspoint";
      String regex = "\s";
      String result = input.replaceAll(regex, "");
      System.out.println("结果: "+result);
   }
}

输出

结果:Hiwelcometotutorialspoint

示例 2

类似地,appendReplacement() 方法接受一个字符串缓冲区和一个替换字符串,并将匹配的字符与给定的替换字符串附加到字符串缓冲区。

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RemovingWhiteSpaces {
   public static void main( String args[] ) {
      Scanner sc = new Scanner(System.in);
      System.out.println("输入输入字符串: ");
      String input = sc.nextLine();
      String regex = "\s";
      String constants = "";
      System.out.println("输入字符串: \n"+input);
      //创建一个 Pattern 对象
      Pattern pattern = Pattern.compile(regex);
      //匹配字符串中的编译模式
      Matcher matcher = pattern.matcher(input);
      //创建一个空的字符串缓冲区
      StringBuffer sb = new StringBuffer();
      while (matcher.find()) {
         constants = constants+matcher.group();
         matcher.appendReplacement(sb, "");
      }
      matcher.appendTail(sb);
      System.out.println("结果: \n"+ sb.toString()+constants );
   }
}

输出

输入输入字符串:
this is a sample text with white space
输入字符串:
this is a sample text with white space
结果:
thisisasampletextwithwhitespaces

示例 3

public class Just {
   public static void main(String args[]) {
      String input = "这是带有空格的示例文本";
      String str[] = input.split(" ");
      String result = "";
      for(int i=0; i<str.length; i++) {
         result = result+str[i];
      }
      System.out.println("结果:"+result);
   }
}

输出

结果:Thisisasampletextwithspaces

相关文章


有用资源