用Java解释正则表达式“ \ s”元字符
子表达式/元字符“\s”与空白等效。
例子1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
String regex = "\\s";
String input = "您好,欢迎来到Nhooo!";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
while(m.find()) {
count++;
}
System.out.println("Number of matches: "+count);
}
}输出结果
Number of matches: 7
例子2
下面的示例读取一个字符串,并删除它们之间的所有多余空格。
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);
//用单个空格替换所有空格字符
String result = matcher.replaceAll(" ");
System.out.print("Text after removing unwanted spaces: \n"+result);
}
}输出结果
Enter a String hello this is a sample text with irregular spaces Text after removing unwanted spaces: hello this is a sample text with irregular spaces
热门推荐
1 祝福语简短七夕
10 最美的留言祝福语简短
11 下雪路滑祝福语简短
12 2026新年祝福语简短语
13 要过年了祝福语简短
14 新年探亲祝福语简短精辟
15 猪年元旦祝福语简短创意
16 庆祝论坛周年祝福语简短
17 对上司的简短祝福语
18 贺卡祝福语情侣搞笑简短