如何使用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 教师闺蜜祝福语简短