Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex to strip leading zeros treated as string

Tags:

java

regex

I have numbers like this that need leading zero's removed.

Here is what I need:

00000004334300343 -> 4334300343

0003030435243 -> 3030435243

I can't figure this out as I'm new to regular expressions. This does not work:

(^0)
like image 652
Horse Voice Avatar asked Apr 15 '15 19:04

Horse Voice


People also ask

How do I remove leading zeros in regex?

Use the inbuilt replaceAll() method of the String class which accepts two parameters, a Regular Expression, and a Replacement String. To remove the leading zeros, pass a Regex as the first parameter and empty string as the second parameter. This method replaces the matched value with the given string.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

How do I remove a specific character from a string in regex?

If you are having a string with special characters and want's to remove/replace them then you can use regex for that. Use this code: Regex. Replace(your String, @"[^0-9a-zA-Z]+", "")

How do you remove leading zeros from a string in C++?

str. erase(0, min(str. find_first_not_of('0'), str. size()-1));


1 Answers

You're almost there. You just need quantifier:

str = str.replaceAll("^0+", "");

It replaces 1 or more occurrences of 0 (that is what + quantifier is for. Similarly, we have * quantifier, which means 0 or more), at the beginning of the string (that's given by caret - ^), with empty string.

like image 150
Rohit Jain Avatar answered Sep 27 '22 20:09

Rohit Jain