Skip to main content

Posts

Showing posts with the label regex

Remove leading repeated occurrence from a string

I used to struggle while working with data across different systems as few systems append zeros to the actual value ex. if the value for a unique id is "345683" the system will give "000345683" but when we need to use this value in to enter data in other system we just need the "345683" and as always regex is the best tool for the job; what it should be depends on the problem specification. The following removes leading zeroes, but leaves one if necessary (i.e. it wouldn't just turn "0" to a blank string). String myDesiredString = inputString.replaceFirst("^0+(?!$)", "") Just a background for first time regex users . ^ anchor will make sure that the 0+ being matched is at the beginning of the input  The (?!$) negative lookahead ensures that not the entire string will be matched Replace the zero with desired character or series of characters to remove the repeated occurrence at the start public static void mai...