Removing Whitespaces Using Regex in Java

In this section, we will write Java programs that remove whitespaces using Regex. To remove whitespaces in Java, use a regular expression pattern to match and replace all whitespace characters in a string. Whitespace characters consist of spaces, tabs, and newline characters.

Example:

Input: String input = "Tutorial    and    Example"

Output: Original String:  Tutorial   and   Example  /p

Result:  TutorialandExample

Methods for Removing whitespaces with Regex:

There are several approaches to whitespace removal using regex; here are some methods:

  1. Using replaceAll() Method
  2. Using Pattern and Matcher classes
  3. Using String.split and String.join with Regex
  4. Using Regular Expression and Java 8 Streams
  5. Using Scanner and Regular Expression

Using replaceAll() Method

The Java code implements a removeWhitespace() method that uses the replaceAll() method and a regex (\\s+) to remove all whitespaces from the input string.

FileName: RemoveSpaces.java

public class RemoveSpaces {

    // Method to remove whitespaces using replaceAll

    public static String removeWhitespace(String input) {

        // Use regex \s+ to match and replace whitespaces

        return input.replaceAll("\\s+", "");

    }

    public static void main(String[] args) {

        // Example usage

        String input = "Tutorial    and    Example";

        System.out.println("Original String: " + input);

        String result = removeWhitespace(input);

        System.out.println("Result: " + result);

    }

}

Output:

Original String:  Tutorial   and   Example

Result:  TutorialandExample

Complexity Analysis: The code has a time complexity of O(n), where n is the input string's length because it iterates through each character once. The space complexity is O(n), as a new string is produced to store the result.

Using Pattern and Matcher classes

The Java code implements a removeWhitespace() method that uses the Pattern and Matcher classes to generate a regex pattern (\\s+) and replace all whitespaces in the input string.

FileName: RemoveSpaces1.java

import java.util.regex.Pattern;

import java.util.regex.Matcher;

public class RemoveSpaces1 {

    // Method to remove whitespaces using Pattern and Matcher

    public static String removeWhitespace(String input) {

        // Create a Pattern with regex \s+

        Pattern pattern = Pattern.compile("\\s+");

        // Use Matcher to find and replace whitespaces

        Matcher matcher = pattern.matcher(input);

        return matcher.replaceAll("");

    }

    public static void main(String[] args) {

        String input = "Tutorial   and   Example";

        System.out.println("Original String: " + input);

        String result = removeWhitespace(input);

        System.out.println("Result: " + result);

    }

}

Output:

Original String:  Tutorial   and   Example

Result:  TutorialandExample

Complexity Analysis: The code's time and space complexity is O(n), where n represents the length of the input string.

Using String.split and String.join

The Java code specifies a removeWhitespace() method that uses String.split("\\s+") to split the input string into parts depending on one or more whitespaces, and then String.join("") to concatenate the portions without whitespaces.

FileName: RemoveSpaces2.java

import java.util.Arrays;

public class RemoveSpaces2 {

    // Method to remove whitespaces using String.split and String.join with regex

    public static String removeWhitespace(String input) {

        // Split the input using regex \s+ and join the parts

        return String.join("", input.split("\\s+"));

    }

    public static void main(String[] args) {

        String input = "Tutorial    and    Example";

        System.out.println("Original String: " + input);

        String result = removeWhitespace(input);

        System.out.println("Result: " + result);

    }

}

Output:

Original String:  Tutorial   and   Example

Result:  TutorialandExample

Complexity Analysis: The code's time and space complexity is O(n), where n represents the length of the input string.

Using Regular Expression and Java 8 Streams

The Java code defines a removeWhitespace() function that uses Java 8 Streams and Patterns.compile("\\s+").splitAsStream(input) splits an input string into non-whitespace tokens and Collectors.joining() to concatenate them.

FileName: RemoveSpaces3.java

import java.util.regex.Pattern;

import java.util.stream.Collectors;

public class RemoveSpaces3 {

    // Method to remove whitespaces using regular expression and Java 8 Streams

    public static String removeWhitespace(String input) {

        return Pattern.compile("\\s+")

                .splitAsStream(input)

                .collect(Collectors.joining());

    }

    public static void main(String[] args) {

        String input = "Tutorial    and    Example";

        System.out.println("Original String: " + input);

        String result = removeWhitespace(input);

        System.out.println("Result: " + result);

    }

}

Output:

Original String:  Tutorial   and   Example

Result:  TutorialandExample

Complexity Analysis: The removeWhitespace() function has a time complexity of O(n), where n is the length of the input string because the splitAsStream() action only iterates through the characters once. The space complexity is O(n) because the split operation generates a stream of substrings, which are then joined into a new string.

Using Scanner and Regular Expression

The code uses a Scanner and regular expressions to remove excessive spaces from an input string. The removeWhitespace() method uses a Scanner with the regular expression \\s+ as a delimiter to break the input string into tokens separated by one or more whitespace characters. The collected tokens are then concatenated with a StringBuilder.

FileName: RemoveSpaces4.java

import java.util.Scanner;

public class RemoveSpaces4 {

    // Method to remove whitespaces using Scanner and regular expression

    public static String removeWhitespace(String input) {

        try (Scanner scanner = new Scanner(input)) {

            // Use \\s+ regex as a delimiter and concatenate the parts

            return scanner.useDelimiter("\\s+").tokens().collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();

        }

    }

    public static void main(String[] args) {

        String input = "Tutorial    and    Example";

        System.out.println("Original String: " + input);

        String result = removeWhitespace(input);

        System.out.println("Result: " + result);

    }

}

Output:

Original String:  Tutorial   and   Example

Result:  TutorialandExample

Complexity Analysis: The time complexity of the code is O(n), where n is the length of the input string because each character is processed once. The space complexity is also O(n), as the Scanner tokens are collected into a StringBuilder, and the necessary space is proportional to the length of the input string.