Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
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
Advertisements