如何使用Java RegEx匹配等效的空白?
元字符“\\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[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "\\s";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
int count = 0;
while(matcher.find()) {
count++;
}
System.out.println("Number of spaces: "+count);
}
}输出结果
Enter a String Hello how are you welcome to nhooo Number of spaces: 6
例子2
import java.util.Scanner;
public class RegexExample {
public static void main( String args[] ) {
//regular expression
String regex = "\\s+";
System.out.println("Enter input value: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String result = input.replaceAll(regex, "");
System.out.println("Result: "+result);
}
}输出结果
Enter input value: hello how are you Result: hellohowareyou
热门推荐
10 毛笔哥哥结婚祝福语简短
11 向国庆送祝福语简短
12 建队节祝福语简短
13 朋友喜得外孙简短祝福语
14 小店营业的祝福语简短
15 餐饮生日祝福语简短独特
16 鲜花英语祝福语卡片简短
17 男朋友暴富祝福语简短
18 婶婶拜年祝福语大全简短