用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