Java program to remove all numbers in a string except "1" and "2"?


  • The regular expression "(?<!\d)digit(?!\d)" matches the digit specified.

  • The replaceAll() method accepts two strings: a regular expression pattern and, the replacement string and replaces the pattern with the specified string.

  • Therefore, to remove all numbers in a string except 1 and 2, replace the regular expressions 1 and 2 with one and two respectively and replace all the other digits with an empty string.

Example

 Live Demo

import java.util.Scanner;
public class RegexExample {
   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();
      //Regular expression to match the digit 1
      String regex1 = "(?<!\d)1(?!\d)";
      //Regular expression to match the digit 2
      String regex2 = "(?<!\d)2(?!\d)";
      //Replacing all space characters with single space
      String result = input.replaceAll(regex1, "one")
         .replaceAll(regex2, "two")
         .replaceAll("\s*\d+", "");
      System.out.print("Result: "+result);
   }
}

Output

Enter a String
sample 1 2 3 4 5 6
Result: sample one two

Updated on: 10-Jan-2020

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements