简体   繁体   中英

How to replace single occurrence of a character in a Java string

I have a string where it contains different combinations of the slashes

{"result":"{\"cov_details\":[{\"issue_date\":\"UNIT 
 OFFICE,NEYVELI\",\"cov\":\"MCWG\"}],\"dl_number\":\"TN31Y200000784\",\"address\":\"PERIYA COLONY  KO 
 PAVAZHANGUDI  VIRUDHACHALAM TK\",\"issue_date\":\"24-03-2010\",\"dob\":\"21-03- 
 1981\",\"name\":\"VICNESWARAN S\",\"blood_group\":\"\",\"validity\":{\"transport\":\"\",\"non- 
 transport\":\"4-01-2010 to 23-03-2040\"},\"father\\\/husband\":\"SELVAM\"}","status- 
 code":"101","request_id":"a2642ae9-2f10-4e9a-9f7e-c3ee1a9a2dbe"}

I want to replace all occurances of a single "" alone but ignore when "" is followed by "/" ( check out the
father\\\/husband\ parameter. It should read father\/husband . How can I achieve this in Java?

Just hide "\/" by replacing it with another character sequence like "~~~", then restore it after:

    String string = "father\\\\\\/husband\\";
    
    System.out.println("Before\t:\t" + string);
    
    System.out.println
    (
        "After\t:\t" + string
                            .replaceAll("\\\\/", "~~~")
                            .replaceAll("\\\\", "")
                            .replaceAll("~~~", "\\\\/")
    );

Output:

Before  :   father\\\/husband\
After   :   father\/husband

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