3

I'm especially terrible with Regex, but reworked one I found online to suit my needs, but it keeps throwing the "no viable alternative at character '\'" error. This pattern works when tested in regex101.com, regexplanet.com, and rubular.com. I thought I had escaped everything that needed escaping. Right, now I'm out of my depth with this. Hopefully someone here can give me some insight.

In case anyone needs to know, the regex needs to find the first email address in an the email body (which is from a submitted form) that immediately follows the word "From:" (at this point I'm unsure if there will be a space after "From:" or not), since there could be multiple email addresses in the text.

Thanks in advance to anyone who can help!

Here's my code:

if (email.Subject.Contains('xxxx') || email.fromAddress == 'xxxx'){
        Pattern myPattern = Pattern.compile('From:(\\s(?:[a-z0-9!#$%&'*+\\/=?^_'{|}~-]+(?:\\.[a-z0-9!#$%&'*+\\/=?^_'{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\]))');
        Matcher myMatcher = myPattern.matcher(email.plainTextBody);
        Set<String> emails = new Set<String>();
        while(myMatcher.find()) {
            emails.add(matcher.group(1));
        }
    }

1 Answer 1

5

You are getting this error message because Apex uses ' to define strings. In your expression, you have this character appearing multiple times, breaking the code. You should just add a \ before them. The code highlight might help you to see where you need to change.

For example:

Pattern.compile('From:(\\s(?:[a-z0-9!#$%&'*+\\/=?^_'{|)...

Would turn into

Pattern.compile('From:(\\s(?:[a-z0-9!#$%&\'*+\\/=?^_\'{|)...
4
  • 2
    In other words, use an IDE that has syntax highlighting, and trust the highlights.
    – sfdcfox
    May 26, 2016 at 18:10
  • Even the Developer Console highlights this. There is literally no setup required. May 26, 2016 at 18:10
  • As does SFSE (finally).
    – Adrian Larson
    May 26, 2016 at 18:31
  • Thanks for the responses! I actually had (or thought I had) escaped the ' (I pasted the wrong version of code in this question). However, I did miss one...sorry for wasting everyone's time! I am curious about the highlights mentioned in Developer Console. I definitely don't have that in mine. I'm very new to SFDC so I may have missed a setting somewhere.
    – Wilock
    May 27, 2016 at 19:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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