This changes the response to aioobe using nested statements instead of a nested loop to generate statements:
public static void main(String... args) { String s = "lorem ipsum dolor sit blah $10 bleh"; System.out.println(s.replaceAll(censorWords("ipsum", "sit", "$10"), "*")); // prints "lorem ***** dolor *** blah *** bleh" } public static String censorWords(String... words) { StringBuilder sb = new StringBuilder(); for (String w : words) { if (sb.length() > 0) sb.append("|"); sb.append( String.format("(?<=(?=%s).{0,%d}).", Pattern.quote(w), w.length()-1 ) ); } return sb.toString(); }
Some key points:
StringBuilder.append in a loop instead of String +=Pattern.quote to avoid any $ or \ in censored words
However, this is not the best solution to the problem. This is just a fun regular expression game to play, really.
Related Questions
- codingBat plusOut using regex
How it works
We want to replace with "*" , so we need to match one character at a time. The question is what kind of character.
This is a symbol where, if you come back long enough, and then you look forward, you see a censoring word.
Here's the regular expression in a more abstract form:
(?<=(?=something).{0,N})
This corresponds to the provisions in which you can return to the characters N , you can look and see something .
polygenelubricants
source share