简体   繁体   中英

How to replace a part of a string with another part?

I have long String like KA01F332-9:25,KA01F212-9:27,KA01F242-9:35,KA01F232-9:45, . These are combination of vehicle no and time. now I want to replace the time of KA01F242 to 10:20 How can I do this.

So far I hav done this.

String busEAT=KA01F332-9:25,KA01F212-9:27,KA01F242-9:35,KA01F232-9:45,;
busEAT.subString(busEAT.indexOf(vno),busEAT.indexOf(','));

but I am not getting the exact value .and it has to be done dynamically can any one help me in this.

You could use regex like this :

    String s = "KA01F332-9:25,KA01F212-9:27,KA01F242-9:35,KA01F232-9:45,";
    System.out.println(s.replaceFirst("(?<=KA01F242-).*?(?=,)", "10:20")); 
   // Positive look-behind for "KA01F242" and positive look-ahead for "," . They are just matched but not captured, so they will not get replaced.

O/P:

KA01F332-9:25,KA01F212-9:27,KA01F242-10:20,KA01F232-9:45,

EDIT :

"(?<=KA01F242-).*?(?=,)", "10:20") --> First looks for any character preceeded by "KA01F242" (positive look-behind), then it selects all the characters ("KA01F242" is just matched, not selected.) Next, all the successive characters are selected until you get a comma (which is agin matched, not selected)

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