简体   繁体   中英

How to replace single quote within a string with two single quotes in java?

I have the below data in my text file.

1|"John"|3,5400
2|"Jim"|7,7300
3|"Smith,Robin",3,4300
4|"O'Brien",10,8200

and I want this output:

(1,'John',3,5400)
(2,'Jim',7,7300)
(3,'Smith,Robin',3,4300)
(4,'O''Brien',10,8200)

Basically I want to replace | character with commas and double quotes with single quote. I am able to achieve that with this piece of code:

String text2 = textAfterHeader.replaceAll("\\|", ",").replaceAll("\"", "'").replaceAll("[a-zA-Z]'[a-zA-Z]", "''");

output that I am getting:

1,'John',3,5400
2,'Jim',7,7300
3,'Smith,Robin',3,4300
4,'''rien',10,8200

But I have one more requirement where I need to put two single quotes whenever a single quote appears between a string, for example, O'Brien as O''Brien. But this part is not working.

As was suggested by @AndyTurner, you can simplify the problem by first replacing all ' with '' and then replace all " with ' . The only thing missing after that are the parenthesis, which can be added in two steps:

  1. Replace all blanks with ) ( (notice the blank between the parenthesis).
  2. Add a leading ( and a trailing ) to the String .

All together, a solution could look like this:

final String output = "(" 
        + input
            .replace("'", "''")
            .replace("\"", "'")
            .replace("|", ",")
            .replace(" ", ") (")
        + ")";

Ideone demo

A possible solution could be:

String lineSeparator = System.getProperty("line.separator");
String output = new StringBuilder("(").append(
        input.replaceAll("\\|", ",")
        .replaceAll("'", "''") // (*)
        .replaceAll("\"", "'") // (**)
        .replaceAll(lineSeparator, ")" + lineSeparator + "("))
        .append(")").toString();

Note the replacement (*) must come before (**). Since you need to replace exact characters instead of variable regular expressions, you want better use replace instead of replaceAll .

Try this regex:

\\s*\\'\\s*

and a call to Replace with " will do the job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM