Remove Leading Zeroes from a String in Java using regular expressions

JavaObject Oriented ProgrammingProgramming

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.


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.out.println("Enter an integer: ");
      String num =;
      String result = LeadingZeroesRE.removeLeadingZeroes(num);


Enter an integer:
Updated on 15-Oct-2019 12:51:11