Remove Leading Zeroes from a String in Java using regular expressions


The replaceAll() method of the String class accepts two strings representing a regular expression and a replacement String and replaces the matched values with given String.

Following is the regular expression to match the leading zeros of a string −

The ^0+(?!$)";

To remove the leading zeros from a string pass this as first parameter and “” as second parameter.

Example

The following Java program reads an integer value from the user into a String and removes the leading zeroes from it using the Regular expressions.

Live Demo

import java.util.Scanner;
public class LeadingZeroesRE {
   public static String removeLeadingZeroes(String str) {
      String strPattern = "^0+(?!$)";
      str = str.replaceAll(strPattern, "");
      return str;
   }
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter an integer: ");
      String num = sc.next();
      String result = LeadingZeroesRE.removeLeadingZeroes(num);
      System.out.println(result);
   }
}

Output

Enter an integer:
000012336000
12336000

Updated on: 15-Oct-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements