I need to find credit card numbers in a chat transcript inside its before insert trigger and x them out. I have the following regex(s) first one works in online tools for long strings containing new lines and finds the patterns, second doesn't work in online tools for a long string containing new lines but works for a one line string.
String regex = '(\\d{4}[- ]){3}\\d{4}|\\d{16}';
String regex = '^(\\d{4}[- ]){3}\\d{4}|\\d{16}$';
Here's my simple method so far which isn't working for a string containing any of the variations such as,
1234 1234 1234 1234
1234-1234-1234-1234
1234123412341234
public static String findByRegexAndReplace(String stringToMatch, String replaceWith, String regex) { String resultString; Pattern patternObj = Pattern.compile(regex); Matcher matcherObj = patternObj.matcher(stringToMatch); System.debug('matcherObj.matches()?'+ matcherObj.matches()); if (matcherObj.matches()){ resultString = matcherObj.replaceAll(replaceWith); for (Integer i=0; i<matcherObj.groupCount(); i++){ System.debug(i +': '+ matcherObj.group(i)); } } return resultString; }
}
matcherObj.matches() returns true only in this case, 1234-1234-1234-1234, but even then matcherObj.replaceAll(replaceWith) throws an exception like it does with every cases. Please help me understand what I'm doing wrong, if it's how I'm using the Matcher class methods or my regex isn't "Apex compatible"? Thanks!