I have cases which contain urls in the case description, and the urls contain whitespace. I need to replace the whitespace with %20 in order to make the links clickable from the case. Obviously the rest of the case description before/after the URLs should remain untouched.

I'm trying to test how to do this in dev console just using an input string for the initial investigation, so far I have:

String inputString = 'John Doe \n Attachments: Download link: \\\\link\\TRA001AAA\\021840136\\some receipt 2021-02-16.pdf \n Claim submission reference number: CS6207713.';
pattern myPattern = pattern.compile('TRA001AAA(.*)'); 
matcher myMatcher = myPattern.matcher(inputString);
System.debug('myMatcher.find() = '+ myMatcher.find());
System.debug('myMatcher.group() = '+ myMatcher.group());
String regExp = '[\\s]';
String noSpaces = myMatcher.group().replaceAll(regExp, '%20');
System.debug('noSpaces = ' + noSpaces);

The debug output is:

DEBUG|myMatcher.find() = true
15:08:46:007 USER_DEBUG [5]|DEBUG|myMatcher.group() = TRA001AAA\021840136\some receipt 2021-02-16.pdf
15:08:46:007 USER_DEBUG [8]|DEBUG|noSpaces = TRA001AAA\021840136\some%20receipt%202021-02-16.pdf%20

I have two problems now

  1. Theres a trailing space in my match, causing the extra %20 at the end
  2. How do I get this back into the original text? So the desired final string would be: 'John Doe \n Attachments: Download link: \\\\link\\TRA001AAA\\021840136\\some%20 receipt%202021-02-16.pdf \n Claim submission reference number: CS12345.
  • 2
    Why not use EncodingUtil.urlEncode(string, encoding) during construction of the original string? It's easier to fix it before the input gets to you than after.
    – sfdcfox
    Feb 24, 2022 at 16:46
  • The cases arrive using email-to-case with the URL. They are generated by a web portal, but the team who own it are too busy to fix this, so I've been asked to put this workaround in place to fix them after creation :(
    – Bob McD
    Feb 24, 2022 at 17:08
  • lol, okay, that makes more sense. I think you should trim() before replacing?myMatcher.group().trim().replaceAll(regExp, '%20');
    – sfdcfox
    Feb 24, 2022 at 17:29
  • Trim is perfect. I'm going to just add the urls to a new field to avoid any danger to original text, so that is perfect. Thank you
    – Bob McD
    Feb 25, 2022 at 10:14


You must log in to answer this question.

Browse other questions tagged .