Regex expressions in Java, \\s vs. \\s+

Regex expressions in Java, \\s vs. \\s+

A Regex (Regular Expression) is used to define a search pattern for text. It is commonly used for pattern matching, validation, search and replacement, text parsing, splitting strings, etc. Java provides a powerful regex (regular expression) API through the java.util.regex package. Among the various regex patterns, \\s and \\s+ are most commonly used to handle whitespaces. 

In this blog, we will learn regex expressions (\\s and \\s+) in more detail.

Table of Contents:

What is \\s in Java Regex?

In Java, \\s is a predefined character class that matches a single whitespace character. It is used to identify and manipulate whitespace in strings, such as splitting text, trimming extra spaces, or validating input formats.

Example of \\s in Java

Code:

import java.util.regex.*;

public class Main {
    public static void main(String[] args) {
        String text = "Hello Intellipaat";
        String regex = "Hello\\sIntellipaat";
        boolean matches = Pattern.matches(regex, text);
        if(matches)
        System.out.println("Strings are same"); 
        else
          System.out.println("Strings are not same");
    }
}

Output:

Strings are same

Explanation: Here, the string text contains whitespace, while the string regex does not contain an actual whitespace but instead uses \\s to represent exactly one whitespace character in a regular expression. After that, we check whether the text matches the regex pattern using a regular expression matching function and yes, it returns that both the strings are exactly the same as expected.

What is \\s+ in Java Regex?

Unlike \\s, which matches only a single whitespace character, \\s+ matches one or more consecutive whitespace characters. The + quantifier means “one or more occurrences” of the preceding character class.

Example of \\s+ in Java Regex

Code:

import java.util.regex.*;

public class Main {
    public static void main(String[] args) {
        String text = "Hello         Intellipaat";
        String regex = "Hello\\s+Intellipaat";
        boolean matches = Pattern.matches(regex, text);
        if(matches)
        System.out.println("Strings are same"); 
        else
          System.out.println("Strings are not same");
    }
}

Output:

Strings are same

Explanation: \\s+ in “Hello\\s+Intellipaat” allows for one or more space characters, so after matching the strings it become same.

Key Differences Between \\s and \\s+

Here are the following differences between \\s and \\s+:

RegexMeaning
\\sIt matches only one whitespace character.
\\s+It matches more than one whitespace character.

Real-life Examples of \\s vs. \\s+ in Java

Here are some of the real-life examples of \\s and \\s+ in Java:

Example 1: Splitting Strings on Whitespace using \\s

If you want to split a string into words containing single whitespace characters, we can consider this example:

Code:

import java.util.regex.*;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String str = "Intellipaat is the best organization";
        String[] words = str.split("\\s");
        System.out.println(Arrays.toString(words));
    }
}

Output:

[Intellipaat, is, the, best, organization]

Example 2: Replacing Multiple Spaces(\\s+) with a Single Space

Code:

import java.util.regex.*;
import java.util.Arrays;
public class Main {
    public static void main(String[] args) {
        String str = "Intellipaat   is    the best   organization";
        String result = str.replaceAll("\\s+", " ");
        System.out.println(result);
    }
}

Output:

Intellipaat is the best organization

Conclusion

So far in this blog, we have learned regex expressions( \\s and \\s+) in Java. We have to use \\s, when we need to work with only one whitespace, while \\s+ is used when more than one whitespaces are required.  If you want to excel in your career in Java, please refer to our advanced Java course.

FAQs

1. What are Regular Expressions in Java?

Regular Expressions (regex) in Java are patterns used for string matching, searching, and manipulation.

2. What does \\ mean in a regex?

In Java regex, \\ is an escape character used to represent special characters. Since Java uses \ as an escape in strings, you need double backslashes (\\) to define regex patterns (e.g., \\d for digits).

3. What is \\ w+?

\\w+ is a regex pattern that matches one or more (+) word characters (\\w).

  • \\w matches letters (A-Z, a-z), digits (0-9), and underscore (_)
  • + ensures at least one character is matched
4. How to generate regex expressions in Java?

Java provides the java.util.regex package with classes like Pattern and Matcher for generating regex expressions.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner