Use \s in Java

Sheeraz Gul Mar 24, 2022
Use \s in Java

This tutorial will discuss and demonstrate the use of \\s in Java.

Use \s as Regular Expression in Java

\\s is a regular expression in Java used for white space characters. Regular expressions are the sequence of characters used to develop a pattern for data.

We use patterns sometimes when we search data in the text, and \\s is used in those patterns when space is required.

We use double backslash because Java syntax does not support the single backslash. In reality, the syntax for a single whitespace character is \s.


package delftstack;

public class Reg_Expression {
    public static final String Demo = "Hello! this is";

    public static void main(String[] args) {
        // Print the original String
        System.out.println("This is the Original String: ");

        // replace all \\s whitespaces with \t tabs
        System.out.println("This is the String \\s replaced with \\t: ");
        System.out.println(Demo.replaceAll("\\s", "\t"));

        //Split the string at \\s means the spaces
        String[] Demo_Split = (Demo.split("\\s"));
        System.out.println("This is the String split at \\s: ");
        for (String Print_String : Demo_Split) {

The code above manipulated the string spaces using \\s. First, it replaced the spaces with tabs and split the string at spaces.


This is the Original String:
Hello! this is
This is the String \s replaced with \t:
Hello!	this	is
This is the String split at \s:
Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

Related Article - Java Regex