如何使用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
热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练