Skip site navigation (1)Skip section navigation (2)
Date:      Wed, 21 May 2003 19:02:24 +0200
From:      Sheldon Hearn <sheldonh@starjuice.net>
To:        freebsd-java@freebsd.org
Subject:   Re: String.replaceAll ' to \'
Message-ID:  <20030521170224.GO3823@starjuice.net>
In-Reply-To: <20030521152846.GA16534@dyn107-dh.nbw.tue.nl>
References:  <20030521152846.GA16534@dyn107-dh.nbw.tue.nl>

next in thread | previous in thread | raw e-mail | index | archive | help

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.



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20030521170224.GO3823>