如何使用 Java 正则表达式(RegEx)删除空格
正则表达式“\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: "+result);
}
}输出
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("Enter input string: ");
String input = sc.nextLine();
String regex = "\s";
String constants = "";
System.out.println("Input string: \n"+input);
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
//Creating an empty string buffer
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
constants = constants+matcher.group();
matcher.appendReplacement(sb, "");
}
matcher.appendTail(sb);
System.out.println("Result: \n"+ sb.toString()+constants );
}
}输出
Enter input string: this is a sample text with white spaces Input string: this is a sample text with white spaces Result: thisisasampletextwithwhitespaces
示例 3
public class Just {
public static void main(String args[]) {
String input = "This is a sample text with spaces";
String str[] = input.split(" ");
String result = "";
for(int i=0; i<str.length; i++) {
result = result+str[i];
}
System.out.println("Result: "+result);
}
}输出
Result: Thisisasampletextwithspaces
广告
数据结构
网络
关系型数据库
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP