Java中使用正则表达式从字符串中删除空格

正则表达式是一个表达式,用于搜索所需模式或匹配所需模式或使用正则表达式根据要求操作输入。此正则表达式可在Java 编程中的java.util.regex.*包中找到。在本文中,我们将学习使用正则表达式删除空格。

使用正则表达式删除空格
这里\\s是简写字符类,用于表示字符串中的任何空白字符。它还可以包含空格、制表符、换行符。+限定符,表示多个空格。最后,所需的正则表达式是\\s+

下面是上述正则表达式的实现:

// Java Program to remove 
// white spaces using regex 
import java.util.regex.*; 

// Main Class 
public class RegexWhiteSpaceExampleOne 

    
// Main method 
    public static void main(String[] args) { 
        
// Input String 
        String inputString =
"     Welcome to GeeksForGeeks         "

        
// Remove white spaces using regex 
        String outputString = inputString.replaceAll(
"\\s+", ""); 

        
// Display the results 
        System.out.println(
"Input String: \"" + inputString + "\""); 
        System.out.println(
"Output String: \"" + outputString + "\""); 
    } 

上述程序的解释:
在上面的代码中,首先我采用一个字符串值,上面已经解释过,然后我使用了replaceAll String方法。我们向此replaceAll 方法传递正则表达式“\s+”。