"\s+"的使用

详解 "\s+"

正则表达式中s匹配任何空白字符,包括空格、制表符、换页符等等, 等价于[ f v]

  • f -> 匹配一个换页
  • -> 匹配一个换行符
  • -> 匹配一个回车符
  • -> 匹配一个制表符
  • v -> 匹配一个垂直制表符

而“s+”则表示匹配任意多个上面的字符。另因为反斜杠在Java里是转义字符,所以在Java里,我们要这么用“\s+”.

那么问题来了,“\s+”有啥使用场景呢?

举例——排序

假设一个输入场景:用冒泡排序算法对一组数字进行从小到大排序

输入:输入的是一行数字,就是我们需要排序的数字

输出:输出是从小到大排序好的数字,数字之间用空格分开

样例输入

2 1 5 8 21 12

样例输出

1 2 5 8 12 21
方法1:
import java.util.Scanner;
public class test{
    public static void main(String[] args) {  
        Scanner sc = new Scanner(System.in);  
        String s = sc.nextLine();//将用户输入的一整行字符串赋给s  
        String[] c = s.split(" ");//用空格将其分割成字符串数组  
        
        int size = c.length;  
        int[] b =new int[size];  
        for (int m = 0; m < b.length; m++) {  
            b[m] = Integer.parseInt(c[m]);//讲字符串数组转换成int数组  
        }  
        int temp=0;  
        for (int i = 0; i < b.length; i++) {  
            for (int j = 0; j < b.length-i-1; j++) {  
                if(b[j]>b[j+1]){  
                    temp=b[j];  
                    b[j]=b[j+1];  
                    b[j+1]=temp;  
                }  
            }  
        }  
          
        for(int n = 0; n < b.length ; n++){  
            System.out.print(b[n]);  
            System.out.print(' ');  
        }  
            sc.close();   
    }
}

方法2:

import java.util.Scanner;
public class test{
    public static void main(String[] args) {  
        Scanner sc = new Scanner(System.in);  
        String s = sc.nextLine();//将用户输入的一整行字符串赋给s  
        String[] c = s.split("\s+");//用空格将其分割成字符串数组  
        
        int size = c.length;  
        int[] b =new int[size];  
        for (int m = 0; m < b.length; m++) {  
            b[m] = Integer.parseInt(c[m]);//讲字符串数组转换成int数组  
        }  
        int temp=0;  
        for (int i = 0; i < b.length; i++) {  
            for (int j = 0; j < b.length-i-1; j++) {  
                if(b[j]>b[j+1]){  
                    temp=b[j];  
                    b[j]=b[j+1];  
                    b[j+1]=temp;  
                }  
            }  
        }  
          
        for(int n = 0; n < b.length ; n++){  
            System.out.print(b[n]);  
            System.out.print(' ');  
        }  
            sc.close();   
    }
}

这两个方法的区别就是

用它:String[] c = s.split(" ");还是用它:String[] c = s.split("\s+");
假如我们输入的是:1 2 3   12  11这样的数据,换言之就是数字之间有多个空格的时候,方法1将会报错,而方法2正常排序运行。因为方法1只能匹配一个空格,而方法2可以匹配多个空格。
原文地址:https://www.cnblogs.com/shixisheng/p/6603701.html