Java Regex to mask alphanumeric string and show last 4 digits You're using replace, which doesn't use regular expressions. Try replaceAll.