You are viewing a plain text version of this content. The canonical link for it is here.
Posted to regexp-user@jakarta.apache.org by Kevin Rodgers <ke...@ihs.com> on 2004/09/10 00:13:44 UTC
search and replace loop example (java.util.regex -> org.apache.regexp)
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? Should Regexp include
a corresponding example in its documentation?
(see http://jakarta.apache.org/regexp/apidocs/org/apache/regexp/RE.html)
Thanks,
--
Kevin Rodgers
---------------------------------------------------------------------
To unsubscribe, e-mail: regexp-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: regexp-user-help@jakarta.apache.org
Re: search and replace loop example (java.util.regex -> org.apache.regexp)
Posted by Kevin Rodgers <ke...@ihs.com>.
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: regexp-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: regexp-user-help@jakarta.apache.org