Computer >> Computer tutorials >  >> Programming >> Java

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

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