Removing leading zeroes in Date String

apexregular-expressionsreplacereplaceallstring

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/6/2022

What I have tried:

String shipDate = '04/06/2022';
String shipDate2 = '04/06/2022';
String shipDate3 = '04/06/2022';
String shipDate4 = '04/06/2022';
system.debug('1::: ' + shipDate.replaceFirst('^0+', ''));
system.debug('2::: ' + shipDate2.replaceFirst('^0+(?!$)', ''));
system.debug('3::: ' + shipDate3.replaceAll('/\b0/g', ''));
system.debug('4::: ' + shipDate4.replaceFirst('\b0/g', ''));

I have tried all of these suggestions: https://stackoverflow.com/questions/8897298/remove-leading-zeroes-in-datestring and can see here https://regex101.com/ that the \b0 works…is there something with apex that doesn't like regex expressions formatted like this?

Best Answer

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.