3

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.

1 Answer 1

5

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());
1
  • Thank you. I think I have to dive deeper into regular expressions now. Commented Oct 30, 2018 at 6:37

You must log in to answer this question.

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