FileDocCategorySizeDatePackage
ReplaceTest.javaAPI DocAndroid 1.5 API4772Wed May 06 22:41:04 BST 2009org.apache.harmony.regex.tests.java.util.regex

ReplaceTest

public class ReplaceTest extends TestCase

Fields Summary
Constructors Summary
Methods Summary
public voidtestCaptureReplace()

        String target, pattern, repl, s;
        Pattern p = null;
        Matcher m;

        target = "[31]foo;bar[42];[99]xyz";
        pattern = "\\[([0-9]+)\\]([a-z]+)";
        repl = "$2[$1]";

        p = Pattern.compile(pattern);
        m = p.matcher(target);
        s = m.replaceFirst(repl);
        assertEquals("foo[31];bar[42];[99]xyz", s);
        s = m.replaceAll(repl);
        assertEquals("foo[31];bar[42];xyz[99]", s);

        target = "[31]foo(42)bar{63}zoo;[12]abc(34)def{56}ghi;{99}xyz[88]xyz(77)xyz;";
        pattern = "\\[([0-9]+)\\]([a-z]+)\\(([0-9]+)\\)([a-z]+)\\{([0-9]+)\\}([a-z]+)";
        repl = "[$5]$6($3)$4{$1}$2";
        p = Pattern.compile(pattern);
        m = p.matcher(target);
        s = m.replaceFirst(repl);
        // System.out.println(s);
        assertEquals("[63]zoo(42)bar{31}foo;[12]abc(34)def{56}ghi;{99}xyz[88]xyz(77)xyz;", s
                );
        s = m.replaceAll(repl);
        // System.out.println(s);
        assertEquals("[63]zoo(42)bar{31}foo;[56]ghi(34)def{12}abc;{99}xyz[88]xyz(77)xyz;", s
                );
    
public voidtestEscapeReplace()

        String target, pattern, repl, s;

        target = "foo'bar''foo";
        pattern = "'";
        repl = "\\'";
        s = target.replaceAll(pattern, repl);
        assertEquals("foo'bar''foo", s);
        repl = "\\\\'";
        s = target.replaceAll(pattern, repl);
        assertEquals("foo\\'bar\\'\\'foo", s);
        repl = "\\$3";
        s = target.replaceAll(pattern, repl);
        assertEquals("foo$3bar$3$3foo", s);
    
public voidtestSimpleReplace()

        String target, pattern, repl;

        target = "foobarfobarfoofo1barfort";
        pattern = "fo[^o]";
        repl = "xxx";

        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(target);

        assertEquals("foobarxxxarfoofo1barfort", m.replaceFirst(repl));
        assertEquals("foobarxxxarfooxxxbarxxxt", m.replaceAll(repl));