1

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.

4
  • try this -- str = str.replace(str.substring(str.indexOf("KA01F242")+9,str.indexOf("KA01F242")+13),"10:20"); Commented Oct 14, 2014 at 12:03
  • @amitbhardwaj Thanks for ur reply, here +9 and +13 dont work for me. I want it has to be dynamic, so num might be vary . . Commented Oct 14, 2014 at 12:08
  • try this ----- String string= str.substring(str.indexOf("KA01F242")+9,str.length()); string = string.replace(string.substring(0, string.indexOf(",")), "10:20"); str = str.substring(0, str.indexOf("KA01F242")+9); str = str+string; Commented Oct 14, 2014 at 12:23
  • here + 9 is for KA01F242- and this is fixed according to your requirement Commented Oct 14, 2014 at 12:25

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.