How to write a regular expression for Salesforce that will identify regex braces and the text between them

264    Asked by Aashishchaursiya in Salesforce , Asked on Feb 24, 2023

I have an email processing class which takes the HTML content of emails, and stores them in rich text fields to be later rendered as PDFs to be printed via VisualForce.


However, the e-mails include some CSS at the start, for example: 'p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px 'Times New Roman'; color: #000000; -webkit-text-stroke: #000000} p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px 'Times New Roman'; color: #000000; -webkit-text-stroke: #000000; min-height: 15.0px} span.s1 {font-kerning: none}'

I am trying to remove this. However, I am having trouble with the parts within curly brackets. When I try to use a regEx to remove curly brackets and all text contained within them, I do this


String regEx = '{.*}';
Email.htmlContent.replaceAll(regEx, '');
It doesn't even make it to the second line. The first throws the error:
Illegal string literal: Invalid string literal '{*}'. Illegal character sequence {' in string literal.
I've confirmed that the regular expression itself should work here: https://regexr.com/3h5ll


Does anyone know how to write a regular expression for Salesforce that will identify curly brackets and the text between them?


Answered by Andrea Bailey

Since backslashes are the escape character in Apex string literals, if you want a literal backlash, you need to escape it with a backslash.


  So the right regex braces to use would be \{.*\}

Your Answer

Interviews

Parent Categories