I am using Java8 and would like to use the following Regex to filter an address from a string, but I get this error:
Error
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 18
(\d+\s*(\w+ ){1,2}${(?i)\b(street|st|road|rd|avenue|ave|drive|dr|loop|court|ct|circle|cir|lane|ln|boulevard|blvd|way)\.?\b}(\s+${(?i)\b(apt|bldg|dept|fl|hngr|lot|pier|rm|ste|slip|trlr|unit|#)\.? *[a-z0-9-]+\b})?)|(${/P\.? ?O\.? *Box +\d+})
^
Code
private static final String REGEX_ROAD = "(?i)\\b(street|st|road|rd|avenue|ave|drive|dr|loop|court|ct|circle|cir|lane|ln|boulevard|blvd|way)\\.?\\b";
private static final String REGEX_APT = "(?i)\\b(apt|bldg|dept|fl|hngr|lot|pier|rm|ste|slip|trlr|unit|#)\\.? *[a-z0-9-]+\\b";
private static final String REGEX_POBOX = "/P\\.? ?O\\.? *Box +\\d+";
private static final String REGEX_STREET = "(\\d+\\s*(\\w+ ){1,2}${"+REGEX_ROAD+"}(\\s+${"+REGEX_APT+"})?)|(${"+REGEX_POBOX+"})";
input = input.replaceAll(REGEX_STREET, "<ADDRESS>");
Any help appreciated.
Entire Class:
package com.jobs.spring.service.replace;
public class ReplaceServiceImpl implements ReplaceService {
private static final String REGEX_ROAD = "(?i)\\b(street|st|road|rd|avenue|ave|drive|dr|loop|court|ct|circle|cir|lane|ln|boulevard|blvd|way)\\.?\\b";
private static final String REGEX_APT = "(?i)\\b(apt|bldg|dept|fl|hngr|lot|pier|rm|ste|slip|trlr|unit|#)\\.? *[a-z0-9-]+\\b";
private static final String REGEX_POBOX = "/P\\.? ?O\\.? *Box +\\d+";
private static final String REGEX_STREET = "(\\d+\\s*(\\w+ ){1,2}${"+REGEX_ROAD+"}(\\s+${"+REGEX_APT+"})?)|(${"+REGEX_POBOX+"})";
@Override
public String removePII(String input) {
input = input.replaceAll(REGEX_STREET, "<ADDRESS>");
return input;
}
public static void main(String[] args) {
ReplaceService rep = new ReplaceServiceImpl();
System.out.println(rep.removePII("1234 Flex Road and 21 happy street"));
}
}
${and the next}after it, that is enough to build a pattern dynamically.