Kevin Rodgers writes:
> The Matcher.appendReplacement method has a great example of how to
> efficiently replace matched text in a loop:
> 
>       Pattern p = Pattern.compile("cat");
>       Matcher m = p.matcher("one cat two cats in the yard");
>       StringBuffer sb = new StringBuffer();
>       while (m.find()) {
>           m.appendReplacement(sb, "dog");
>       }
>       m.appendTail(sb);
>       System.out.println(sb.toString());
> 
> (see http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Matcher.html)
> 
> What's the corresponding code using the RE class?

Here's what I've come up with:

        RE re = new RE("cat");
        String s = "one cat two cats in the yard";
        StringBuffer sb = new StringBuffer();
        int i = 0;
        while (re.match(s, i)) {
            sb = sb.append(s.subSequence(i, re.getParenStart(0)));
            sb = sb.append("dog");
            i = re.getParenEnd(0)
        }
        if (i == 0)
           System.out.println(s);
        else {
           sb = sb.append(s.substring(i));
           System.out.println(sb.toString());
        }

Comments?

-- 
Kevin Rodgers


---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to