The difference between split splitting strings with spaces \t \n \r \f and \s in Java

1. Introduction to various blank separators

\t: tab character, equivalent to tab

\n: Newline

\r: carriage return

\f: Form feed

\s: Common in java regular expressions, such as java matching, replacement, split string (matches, split)

example:

"Java is fun".matches("Java.*") //返回true

2. Correctly use split to separate blank characters

public class demo {
    public static void main(String[] args)  {
        String line = new Scanner(System.in).nextLine();
        String[] s1 = line.split(" ");
        String[] s2 = line.split("\\t");
        String[] s3 = line.split("\\s");
        String[] s4 = line.split("\\s+");
        System.out.print("一个空格:");
        for(String s : s1) {
            System.out.print(s + ",");
        }
        System.out.println("\n------------------------------->=_=");
        System.out.print("\\t:");
        for(String s : s2) {
            System.out.print(s + ",");
        }
        System.out.println("\n------------------------------->=_=");
        System.out.print("\\s:");
        for(String s : s3) {
            System.out.print(s + ",");
        }
        System.out.println("\n------------------------------->=_=");
        System.out.print("\\s+:");
        for(String s : s4) {
            System.out.print(s + ",");
        }
    }
}


Enter: hello my lovely world! (one space, two spaces, and one tab)

3. Instructions for use of \\s


1. \\s instead of \s:
the backslash is a special character that starts an escape sequence in a string. The sign "\" is endowed with a special meaning in the regular expression. At this time, you need to add \ before the character causing ambiguity to tell the compiler: this character is just an ordinary character. So when we want to match "\s" in regular expressions, we need to add escape to "\\s".

2. The relationship between \s and \t\n\r\f and ' ': the
blank character is ' ', '\t', '\n', '\r', or '\f'. Therefore, [\t\n\r\f] is used to represent blanks, and \s is equivalent to [\t\n\r\f].

3. \\s+:
In java regular expressions, p* represents 0 or multiple occurrences of pattern p, p+ represents 1 or multiple occurrences of pattern p, and p? represents 0 or 1 occurrence of pattern p. So we usually use \s+ when doing questions. Just like the above code, \s will have problems when dealing with multiple consecutive spaces, and you need to use \s+.
 

Guess you like

Origin blog.csdn.net/LiZhen314/article/details/130887159