2

I found a Regex which retrieves the Parent domain from a URL. When I tried using the same Regex Expression in Apex using Pattern and Matcher, it's giving me an error of:

Illegal string literal: Invalid string literal '(\w+.\w+)$'. Illegal character sequence \w' in string literal.

Below is my code:

Account aa = [SELECT id, Website from Account WHERE Id = '0016F00002QeRqw'];
String d = aa.Website;
String regexx = '(\w+\.\w+)$';
Pattern mPat = Pattern.compile(regexx);
Matcher myMatch = mPat.matcher(d);
system.debug('--'+myMatch);

Link to the Regex

I am not that good in the Regex and could use some help finding the issue.

4

Apex Pattern class behaves like Java Pattern class. According to Java documentation you have to escape backslash if it is present in regex expression

The backslash character ('\') serves to introduce escaped constructs, as defined in the table above, as well as to quote characters that otherwise would be interpreted as unescaped constructs. Thus the expression \\ matches a single backslash and \{ matches a left brace.


Just escape \ in your regex with additional backslashes. You want to have regex (\\w+\\.\\w+)$


Account aa = [SELECT id, Website from Account WHERE Id = '0016F00002QeRqw'];
String d = aa.Website;
String regexx = '(\\w+\\.\\w+)$';
Pattern mPat = Pattern.compile(regexx);
Matcher myMatch = mPat.matcher(d);
myMatch.find();
System.debug('Domain:' + myMatch.group());
  • Thank you. I think I have to dive deeper into regular expressions now. – Kamal Thakur Oct 30 '18 at 6:37

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.