4

I have an e-mail processing class which takes the HTML content of e-mails, and stores them in rich text fields to be later rendered as PDF's 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?

1 Answer 1

7

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 to use would be \\{.*\\}

2
  • But I don't want a literal backslash. I want it to escape the curly bracket. (I'll note, this works, but I don't fully understand why). Commented Nov 13, 2017 at 2:37
  • 3
    @LucidLunatic curly braces are normally used for counts (e.g. hel{2}o matches hello, as l{2} means "two instances of l"). To match literal curly braces, you have to escape them with \ . However, Apex Code uses \ as an escape, too, so you have to "escape the escape". You'll need to do this almost every time you want to use any sort of special characters in your regexp literally, which will happen more frequently than not. Now that to match a literal \ , you have to end up writing \\\\ . Once you understand that, you should be good to go.
    – sfdcfox
    Commented Nov 13, 2017 at 3:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .