Matching Nonprintable Characters using Java regex



There are 7 common non printable characters used in general and each character has its own hexadecimal representation.

Name characters Hexa-decimal representation
bell \a 0x07
Escape \e 0x1B
Form feed \f 0x0C
Line feed \n 0x0A
Carriage return \r 0X0D
Horizontal tab \t 0X09
Vertical tab \v 0X0B

Example 1

 Live Demo

Following Java program accepts an input text and counts the number of tab spaces in it −

import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample1 {    public static void main(String[] args) {       Scanner sc = new Scanner(System.in);       System.out.println("Enter input text: ");       String input = sc.nextLine();       String regex = "\t";       //Creating a pattern object       Pattern pattern = Pattern.compile(regex);       //Matching the compiled pattern in the String       Matcher matcher = pattern.matcher(input);       int count =0;       while (matcher.find()) {          count++;       }       System.out.println("Number of tab spaces in the given iput text: "+count);    } }

Output

sample text with tab spaces Number of tab spaces in the given input text: 3

Example 2

 Live Demo

You can also use the respective hexa-decimal representations of the non-printable characters to match.

import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample1 {    public static void main(String[] args) {       Scanner sc = new Scanner(System.in);       System.out.println("Enter input text: ");       String input = sc.nextLine();       String regex = "\x09";       //Creating a pattern object       Pattern pattern = Pattern.compile(regex);       //Matching the compiled pattern in the String       Matcher matcher = pattern.matcher(input);       int count =0;       while (matcher.find()) {          count++;       }       System.out.println("Number of tab spaces in the given iput text: "+count);    } }

Output

Enter input text: sample data with tab spaces Number of tab spaces in the given input text: 4
Updated on: 2020-01-13T06:06:18+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements