String replaceAll fails

T

Tim

// what's wrong with this code?

public class TestReplaceAll {


public static void main(String[] args) {

String techName = "O'brien, Jones";
String replacement = "\\'";
System.out.println( techName.replaceAll("[']", replacement) );
System.out.println( techName.replaceAll("[']", "\'" ) );
System.out.println( techName.replaceAll("[']", "\\'" ) );
System.out.println( techName.replaceAll("[']", "\\''" ) );
}
}

// here's the output
O'brien, Jones
O'brien, Jones
O'brien, Jones
O''brien, Jones

// And here's the documentation on the replaceAll function:
replaceAll
public String replaceAll(String regex,
String replacement)Replaces each substring of
this string that matches the given regular expression with the given
replacement.
An invocation of this method of the form str.replaceAll(regex, repl)
yields exactly the same result as the expression
El bugaroo!
TimJowers
 
J

Josh Martin

// what's wrong with this code?

Looks like it's working fine to me - what did you expect as output?
 
A

Andrew Thompson

// what's wrong with this code?

public class TestReplaceAll {


public static void main(String[] args) {

String techName = "O'brien, Jones";
String replacement = "\\'";

techName = techName.replaceAll("[']", replacement);
System.out.println( techName );
....
 
T

Tim

The bug was mine/documentation.

public String replaceAll(String regex,String replacement)
Replaces each substring of this string that matches the
given regular expression with the given replacement.

I assumed they meant "replacement [String]" but they meant
"replacement [special set of characters]". Where the special set of
characters is at least partially defined in the doc for the Matcher
class and means you'll get unexpected behavior if the replacement
String contains \ or $ and you did not realize the behavior is that of
Matcher.replaceAll.

The correct solution for me was
techName = techName.replaceAll("[']", "\\\\'");
as I needed to change each ' to a \' for use as parameters to a
javascript function.

Maybe someone has written a RegEx class that uses methods and
attributes rather than special characters to carry out its functions?
Thanks for the feedback,
TimJowers
 
J

Josh Martin

Tim -

Welcome to the wonderful world of regular expressions in Java :)

Escaping characters is a bit unwieldy - I always forget the part of setting
the original String (i.e. techName = techName.replaceAll...).

Josh
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top