String.replaceAll ' to \'

Sheldon Hearn sheldonh at starjuice.net
Wed May 21 10:02:28 PDT 2003


On (2003/05/21 17:28), Rene Ladan wrote:

> does anybody know how to convert a string with String.replaceAll,
> replacing all ' with \'  occurences?
> 
> or should I just use a loop?

String input = "What's the story's story?";
String output = input.replaceAll("'", "\\\\'");

I used the following class to test this:

public class TestReplaceAll {
    public static void main(String[] args) {
        String input = "";
        String regex = "";
        String replacement = "";
        try {
            input = args[0];
            regex = args[1];
            replacement = args[2];
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(
                "usage: java TestReplaceAll input regex replace");
            System.exit(1);
        }

        String output = input.replaceAll(regex, replacement);
        System.out.println(output);
        System.exit(output.equals(input) ? 1 : 0);
    }
}

I'd imagine this has more to do with The Java Language spec's take on
literal string specification than it has to do with the specifics of
String.replaceAll().

Ciao,
Sheldon.


More information about the freebsd-java mailing list