Matching Nonprintable Characters using Java regex

JavaObject Oriented ProgrammingProgramming

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

NamecharactersHexa-decimal representation
bell\a0x07
Escape\e0x1B
Form feed\f0x0C
Line feed\n0x0A
Carriage return\r0X0D
Horizontal tab\t0X09
Vertical tab\v0X0B

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
raja
Published on 13-Jan-2020 10:34:42
Advertisements