I have a pretty simple code and in one case it works, and not in all the case, I wanted to know what I'm missing I'm trying to match a date in this format dd/mm/yyyy

This is my code:

String d = '20/03/2020';
System.debug(Pattern.matches('(0[1-9]|1[012])/(0[1-9]|[12][0-9]|3[01])/([0-9]{4})', d)); // returns false
d.replace('(0[1-9]|1[012])/(0[1-9]|[12][0-9]|3[01])/([0-9]{4})', 'test');
System.debug(d); //returns D inchanged : 20/03/2020 and not 'test'

I also tried to simply the regex and there the Pattern function works...

String d = '20/03/2020';
System.debug(Pattern.matches('[0-9]{2}/[0-9]{2}/[0-9]{4}', d)); // returns true
d.replace('([0-9]{2}/[0-9]{2}/[0-9]{4})', 'test');
System.debug(d); //returns d inchanged : 20/03/2020 and not 'test'

I've tried many many many solution and regexs and I can't figure out why in a particular case it seems to works


1 Answer 1


There are two issues:

  1. replace(String target, String replacement) doesn't take a regExp as input, but a literal string.
    You should have used replaceAll(String regExp, String replacement)
  2. Strings are immutable, so doing d.replace() or d.replaceAll() will not change that instance. Indeed they return a new string, so you should assign it to d.

Therefore the code should look like:

String d = '20/03/2020';
System.debug(Pattern.matches('[0-9]{2}/[0-9]{2}/[0-9]{4}', d)); // true
d = d.replaceAll('[0-9]{2}/[0-9]{2}/[0-9]{4}', 'test');
System.debug(d); // test

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.