How to remove leading zeros from alphanumeric text?
How to remove leading zeros from alphanumeric text?
https://stackoverflow.com/questions/2800739/how-to-remove-leading-zeros-from-alphanumeric-text
I've seen questions on how to prefix zeros here in SO. But not the other way!
Can you guys suggest me how to remove the leading zeros in alphanumeric text? Are there any built-in APIs or do I need to write a method to trim the leading zeros?
Example:
01234 converts to 1234
0001234a converts to 1234a
001234-a converts to 1234-a
101234 remains as 101234
2509398 remains as 2509398
123z remains as 123z
000002829839 converts to 2829839
javastringalphanumeric
se-share-sheet#willShow s-popover:shown->se-share-sheet#didShow">Share
edited May 22, 2012 at 10:31
- repetitions, lookarounds, and anchors
String.replaceFirst(String regex)
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 ?
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
Time Complexity: O(N)
Auxiliary Space: O(N)
Space-Efficient Approach:
Follow the steps below to solve the problem in constant space using Regular Expression:
Below is the implementation of the above approach:
// Java Program to implement// the above approachimportjava.util.regex.*;classGFG{// Function to remove all leading// zeros from a a given stringpublicstaticvoidremoveLeadingZeros(String str){// Regex to remove leading// zeros from a stringString regex ="^0+(?!$)";// Replaces the matched// value with given stringstr = str.replaceAll(regex,"");System.out.println(str);}// Driver Codepublicstaticvoidmain(String args[]){String str ="0001234";removeLeadingZeros(str);}}