

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to match a white space equivalent using Java RegEx?
The metacharacter "\\s" matches the white space characters in the given string.
Example 1
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main(String args[]) { //Reading String from user System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String regex = "\\s"; //Compiling the regular expression Pattern pattern = Pattern.compile(regex); //Retrieving the matcher object Matcher matcher = pattern.matcher(input); int count = 0; while(matcher.find()) { count++; } System.out.println("Number of spaces: "+count); } }
Output
Enter a String Hello how are you welcome to tutorialspoint Number of spaces: 6
Example 2
import java.util.Scanner; public class RegexExample { public static void main( String args[] ) { //regular expression String regex = "\\s+"; System.out.println("Enter input value: "); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String result = input.replaceAll(regex, ""); System.out.println("Result: "+result); } }
Output
Enter input value: hello how are you Result: hellohowareyou
- Related Questions & Answers
- How to match a non-white space equivalent using Java RegEx?
- How to match word characters using Java RegEx?
- How to match word boundaries using Java RegEx?
- How to match any character using Java RegEx
- How to remove white spaces using Java Regular Expression (RegEx)
- How to match a non-word character using Java RegEx?
- How to match a range of characters using Java regex
- How to match digits using Java Regular Expression (RegEx)
- How to match non-word boundaries using Java RegEx?
- How to match a fixed set of characters using Java RegEx
- How match a string irrespective of case using Java regex.
- How to match non-digits using Java Regular Expression (RegEx)
- How to match end of the input using Java RegEx?
- How to match end of a particular string/line using Java RegEx
- How to match beginning of a particular string/line using Java RegEx
Advertisements