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).

s.replaceFirst("^0+(?!$)", "")

The ^ 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.

Test harness:

String[] in = {
    "01234",         // "[1234]"
    "0001234a",      // "[1234a]"
    "101234",        // "[101234]"
    "000002829839",  // "[2829839]"
    "0",             // "[0]"
    "0000000",       // "[0]"
    "0000009",       // "[9]"
    "000000z",       // "[z]"
    "000000.z",      // "[.z]"
};
for (String s : in) {
    System.out.println("[" + s.replaceFirst("^0+(?!$)", "") + "]");
}

See also

  • regular-expressions.info
    • repetitions, lookarounds, and anchors
  • String.replaceFirst(String regex)
Answer from polygenelubricants on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › java string › remove leading and trailing characters from a string
Remove Leading and Trailing Characters from a String | Baeldung
January 8, 2024 - Return an empty String, or a String containing a single zero? We’ll see implementations for both use cases in each of the solutions. We have unit tests for each implementation, which you can find on GitHub. In our first solution, we’ll create a StringBuilder with the original String, and we’ll delete the unnecessary characters from the beginning or the end: String removeLeadingZeroes(String s) { StringBuilder sb = new StringBuilder(s); while (sb.length() > 0 && sb.charAt(0) == '0') { sb.deleteCharAt(0); } return sb.toString(); } String removeTrailingZeroes(String s) { StringBuilder sb = new StringBuilder(s); while (sb.length() > 0 && sb.charAt(sb.length() - 1) == '0') { sb.setLength(sb.length() - 1); } return sb.toString(); }
Discussions

removing leading zeroes from text variable | OutSystems
I have a input variable that contains leading zeroes. I need to removed the leading zeroes to use as a filter into a table. I can use · to remove the leading zeroes via java script. But I cannot find out how to use this as part of a filter on a table. Any suggestions More on outsystems.com
🌐 outsystems.com
December 16, 2019
Remove Leading Zeros with NumberFormat
Think you need to use the format ... can replace leading zero's with any character you want. ... What I'm looking for is a method in the NumberFormat class which lets one change the leading character to either a space or an *. I'm trying to see if Java is still trying to discover ... More on experts-exchange.com
🌐 experts-exchange.com
September 6, 2008
apex - Removing leading zeroes in Date String - Salesforce Stack Exchange
I have checked a number of posts and regex examples but for some reason I can't get the leading 0's to be removed from the date string below. Can anyone see what I am doing wrong? wanted result: 4/... More on salesforce.stackexchange.com
🌐 salesforce.stackexchange.com
April 13, 2022
How to remove leading zeros from Strings in java - Stack Overflow
I am aware that we can use String Utils library. But what if the String has only "0". It returns " ". Do we have any other way to remove leading 0 for all other strings except for "0". Here is the More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › java › remove-leading-zeros-from-string-in-java
Remove Leading Zeros From String in Java - GeeksforGeeks
August 24, 2026 - If the string contains only zeros, it returns "0". For "00000123569", the output is "123569". Java's String.replaceFirst() can be used with a regular expression to remove leading zeros.
🌐
Coderanch
coderanch.com › t › 590739 › java › Remove-leading-zeros-xx
Remove leading zeros up to 0.xx [Solved] (Java in General forum at Coderanch)
So: 000756.90 becomes 756.90, and 0000070.50 should become 70.50 It seems like I want to do two things: 1. replace all instances of "00." with "0.", recursively, in case it's all leading zeros, and 2. remove all zeros that occur before a pattern that begins with a non-zero digit and ends with a decimal
🌐
TutorialsPoint
tutorialspoint.com › article › explain-how-to-remove-leading-zeroes-from-a-string-in-java
Explain how to remove Leading Zeroes from a String in Java
June 29, 2020 - Whenever you read an integer value into a String, you can remove leading zeroes of it using StringBuffer class, using regular expressions or, by converting the given String to character array.
🌐
Qvera
qvera.com › kb › index.php › 426 › how-to-remove-leading-zeros-or-other-character-from-a-string
How to remove leading zeros or other character from a string. - Knowledge Base - Qvera
March 11, 2014 - There are several ways to strip leading characters and some are better suited for a given situation than others. For example, if the source data is a zero padded number you could use math or number functions. Alernatively if the source data contains alpha characters then string funtions may ...
Find elsewhere
🌐
Quora
quora.com › How-do-you-remove-leading-zeros-from-a-string
How to remove leading zeros from a string - Quora
Answer (1 of 3): The below C++ program removes all leading zeros from a user-entered input string. It should be fairly easy to translate to C or Java. The program is shown twice, once with proper line formatting, and the other with formatting preserved which should be ok to cut and paste into a p...
🌐
OutSystems
outsystems.com › forums › discussion › 55585 › removing-leading-zeroes-from-text-variable
removing leading zeroes from text variable | OutSystems
December 16, 2019 - I have a input variable that contains leading zeroes. I need to removed the leading zeroes to use as a filter into a table. I can use · to remove the leading zeroes via java script. But I cannot find out how to use this as part of a filter on a table. Any suggestions
🌐
Experts Exchange
experts-exchange.com › questions › 23709161 › Remove-Leading-Zeros-with-NumberFormat.html
Solved: Remove Leading Zeros with NumberFormat | Experts Exchange
September 6, 2008 - As I understand you need to change only the line in where the NumberFormat instance created if so You may extend the DecimalFormat and override the format methods to replace leading characters , instead of searching a way which seams not possible ... The answer is, no, there is no concrete NumberFormat class that does *exactly* what you want it to do in the Java JDK.
Top answer
1 of 2
2

If you really want a locally formatted date, you can use Date.parse and Date.format:

String shipDate = '04/06/2022';
System.debug(Date.parse(shipDate).format());

However, be aware that Date.parse depends on the user locale, and the format method also depends on the user locale. In other words, this answer will only work if the date is formatted in the correct locale for the user.


A more literal interpretation, we can split, format, and join, like this:

String shipDate = '04/06/2022';
String[] values = shipDate.split('/');
for(Integer i = 0; i < values.size(); i++) {
    values[i] = Integer.valueOf(values[i])+'';
}
System.debug(String.join(values,'/'));

For a Regular Expression approach, you can use:

String shipDate = '04/06/2022';
// Option 1:
shipDate = shipDate.replaceAll('\\b0(\\d)','$1');
// Option 2:
shipDate = shipDate.replaceAll('\\b0','');
System.debug(shipDate);

Note that if a Regular Expression wants an escaped character, such as \b or \d, you need to escape it again, because that's also Apex's escape character. This is why you see \\b and \\d in the example above.

Also note that Apex's Regular Expression format is closer to Java, not JavaScript, so /.../g doesn't actually do a global search, but just tries to match those characters. To enable the "g" flag, you have to do something like '(?g)\\b0' instead. Regardless, you don't need to, because replaceAll implies g.

You'll want to read Java's Pattern documentation for more information.

2 of 2
0

The formatting of date is best done via DateTime.format(...):

Converts the date to the specified time zone and returns the converted date as a string using the supplied Java simple date format.

Unfortunately converting a String such as 04/06/2022 into DateTime runs into a problem: neither Date nor DateTime support arbitrary formats for parsing. They assume you'll present a String in the current user's locale. While this is certainly doable for a well-known, fixed locale, in a more general case this becomes cumbersome. JSON to the rescue!

In JSON, the date/time format is not standardized...but it is standardized in JavaScript via ISO 8601. Many JSON implementations follow the "JSON is JavaScript" dogma and adopt ISO 8601 format as a best practice/convention:

Date: 2022-04-13 Date and time in UTC:

  • 2022-04-13T18:26:19+00:00
  • 2022-04-13T18:26:19Z
  • 20220413T182619Z

Salesforce's JSON serialization/deserialization engine happens to use ISO 8601. The timezone does matter when you're dealing with string/date conversion. If you omit the timezone, results can be confusing. This example does everything in GMT:

String shipDate = '04/06/2022'; // assume GMT
String[] shipDate_parts = shipDate.split('/');
String shipDate_iso8601 = String.format(
    '{0}-{1}-{2}T00:00:00Z', // YYYY-MM-DD:..
    new List <Object> {
        shipDate_parts[2],
        shipDate_parts[0],
        shipDate_parts[1]
    });

DateTime dt = (DateTime) JSON.deserialize('"' + shipDate_iso8601 + '"', DateTime.class);
String shipDateWithoutZeros = dt.format('M/d/yyyy', 'GMT');

System.debug(shipDate + ' -> ' + dt + ' -> ' + shipDateWithoutZeros);

prints

04/06/2022 -> 2022-04-06 00:00:00 -> 4/6/2022

to the debug log

🌐
CSDN
cnblogs.com › kungfupanda › p › 15989471.html
Java Regular Expression Remove Leading Zeros Example - 功夫 熊猫 - 博客园
March 10, 2022 - You can visit Java String to Int example & int to String example for more details. This is the easiest approach among all others, provided if you can use a third-party library. Apache commons StringUtils class provides a very handy method stripStart that can be used to remove leading zeros from the source string as given below.
Top answer
1 of 2
5

I am aware that we can use String Utils library. But what if the String has only "0". It returns " ". Do we have any other way to remove leading 0 for all other strings except for "0".

You can create your own utility method that does exactly what you want.

Well you still haven't answered my question about whether the department can be alphanumeric or just numeric.

Based on your examples you could just convert the String to an Integer. The toString() implementation of an Integer removes leading zeroes:

    System.out.println( new Integer("008").toString() );
    System.out.println( new Integer("000").toString() );
    System.out.println( new Integer("111").toString() );

If the string can contain alphanumeric the logic would be more complex, which is why it is important to define the input completely.

For an alphanumeric string you could do something like:

StringBuilder sb = new StringBuilder("0000");

while (sb.charAt(0) == '0' && sb.length() > 1)
    sb.deleteCharAt(0);

System.out.println(sb);

Or, an even more efficient implementation would be something like:

int i = 0;

while (product.charAt(i) == '0' && i < product.length() - 1)
    i++;

System.out.println( product.substring(i) );

The above two solutions are the better choice since they will work for numeric and alphanumeric strings.

Or you could even use the StringUtils class to do what you want:

String result = StringUtils.removeleadingZeroes(...) // whatever the method is

if (result.equals(" "))
    result = "0";

return result;

In all solutions you would create a method that you pass parameter to and then return the String result.

2 of 2
2

If you want to use a regex based approach, then one option would be to greedily remove all zeroes, starting from the beginning, so long as we do not replace the final character in the string. The following pattern does this:

^0+(?=.)

The lookahead ensures that there is at least one digit remaining, hence, a final zero will never be replaced.

String input1 = "040008";
String input2 = "000008";
String input3 = "000000";
input1 = input1.replaceAll("^0+(?=.)", "");
input2 = input2.replaceAll("^0+(?=.)", "");
input3 = input3.replaceAll("^0+(?=.)", "");
System.out.println(input1);
System.out.println(input2);
System.out.println(input3);

40008
8
0

Demo

By the way, I like the answer by @camickr and you should consider that as an option.

🌐
w3resource
w3resource.com › java-exercises › re › java-re-exercise-10.php
Java - Remove leading zeros from a given IP address
Write a Java program to remove leading zeros from each octet of an IP address using regex replacement.
🌐
Oracle
forums.oracle.com › ords › apexds › post › remove-leading-zeros-from-string-7987
remove leading zeros from string - Oracle Forums
June 10, 2009 - I am working on a report and I am having a little issue with the output. I have several dollar amount fields that I need to format with only the decimal place. The amount fields are coming in as strin...
🌐
SAP Help Portal
help.sap.com › docs › SUPPORT_CONTENT › java › 3354613040.html
Remove Leading and Trailing Zeros from a String | SAP Help Portal
Java Management Extension (JMX) Database access · Remove Leading and Trailing Zeros from a String · Collection Framework for Java Message Mapping · Duplications in HashMap in Collection Framework · Excel creation using Apache POI APIs in EJB and exposing it as web service.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › remove-leading-zeros-from-a-number-given-as-a-string
Remove leading zeros from a Number given as a string - GeeksforGeeks
July 15, 2025 - 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.
🌐
Reddit
reddit.com › r/learnjava › how to preserve leading zeroes while converting an integer to string?
r/learnjava on Reddit: How to preserve leading zeroes while converting an integer to string?
August 9, 2024 -

For those thinking, I want a quick solution to this problem.Here's the complete solution to this problem, but this is not a college assignment where I'd copy-paste answers to submit as fast as possible. I am learning for myself, for myself to build programming logic. https://github.com/MdRubelRana/Solution-of-all-problem-from-Y.-Daniel-Liang-10th-edition/blob/master/Chapter%2003/Chapter%2003%20Problem%2009%20(Business%20check%20ISBN-10).java

Let's start my question.

I create a variable to store ISBN9. And another one to save that variable as ISBN9 variable will get manipulated later. Say that variable is saved_ISBN9.

Then, I find d9,d8...d1 accordingly, correctly. In the same time, I manipulate the ISBN9 variable to get the remaining ISBN9.

I calculated checksum.

Finally, I want to concatentate ISBN9 with its checksum. Here's where the issue occurred.

    if (checkSum == 10) {
        checkSumStr = "X";
    } else {
        checkSumStr = Integer.toString(saved_ISBN9);
    }

I am losing the leading zeroes in integer as integer never really has "leading" zeroes, as per se. Is there anyway to not drastically change my program logic and still preserve leading zeroes while converting to string?

🌐
Reddit
reddit.com › r/learnpython › removing leading zeroes from list
r/learnpython on Reddit: removing leading zeroes from list
May 17, 2020 -

Hi all,
let's say i have a list

result = [0, 0, 4, 5, 1, 3]

and i want to remove the leading zeroes from that list.

here is my code, is it pythonic?

for i in range(len(result)):
    if result[i] != 0:
        result = result[i:]
        break

this is part of the exercise, in the book 'Elements of programming interviews' i found code that is more complicated and i tottaly don't get it (but it works)

result = result[next((i for i, x in enumerate(result) if x != 0), 
    len(result)):] or [0]

can someone explain me this? this is the best way to make it? I have read about next() function and i get that in the end this is result = result[2:].

🌐
SAP Community
community.sap.com › t5 › technology-q-a › json-string-to-integer-in-groovy-script-removing-leading-zero-s › qaq-p › 13612023
JSON string to integer in groovy script removing leading zero's
February 29, 2024 - If you want to keep using the leading zeros, you have to get rid of your code line where you convert it to double and parse it to integer: ... this line of coding will always remove the leading zeros. Get rid of the "toDouble().intValue()".