Replacing all occurances of a given pattern using Regex

Posted by {"name"=>"Palash Ray", "email"=>"paawak@gmail.com", "url"=>"https://www.linkedin.com/in/palash-ray/"} on July 30, 2008 · 1 min read

    /**
     * Replaces all occurances of the pattern regex with the String
     * replacement
     *
     * @param hayStack
     */
    private String replaceAllWithRegex(String hayStack) {
        String replacement = "replacement";
        String regex = "nsw*:";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(hayStack);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, replacement);
        }
        matcher.appendTail(sb);
        return sb.toString();
    }