如何使用 Java RegEx 匹配空格等价物?
javaobject oriented programmingprogramming
元字符"\s"与给定字符串中的空格字符匹配。
示例 1
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { 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); int count = 0; while(matcher.find()) { count++; } System.out.println("空格数:"+count); } }
输出
输入一个字符串 Hello how are you welcome to tutorialspoint 空格数:6
示例 2
import java.util.Scanner; public class RegexExample { public static void main( String args[] ) { //正则表达式 String regex = "\s+"; System.out.println("输入输入值:"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String result = input.replaceAll(regex, ""); System.out.println("结果:"+result); } }
输出
输入输入值: hello how are you 结果:hellohowareyou