Technical blog

July 30, 2008

Replacing all occurances of a given pattern using Regex

Filed under: java — Tags: — paawak @ 11:43

    /**

     * Replaces all occurances of the pattern regex with the String

     * replacement

     * 

     * @param hayStack 

     */

    private String replaceAllWithRegex(String hayStack) {

        String replacement = "replacement";

        String regex = "ns\w*:";

        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();

    }

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress