2
String Checkout = D:\ifs\APP\Checkout
String DeleteLine = D:\IFS\APP\Checkout\trvexp\client\Ifs.App\text.txt

Note the ifs and IFS in both Strings. I want to replace the Checkout String in the Deleted Line

So the final String would look like this:

\trvexp\client\Ifs.App\text.txt

Following is what I have tried, but obviously due to Case Sensitivity, the string won't get replaced. Any Solution or a work around for this?

String final = DeleteLine.replace(Checkout, "");
3

4 Answers 4

8

String.replace() doesn't support regex. You need String.replaceAll().

DeleteLine.replaceAll("(?i)" + Pattern.quote(Checkout), "");
2
  • 1
    you may use replaceFirst also. Jun 26, 2015 at 6:25
  • Thanks a lot. This worked :) I'll accept the answer in a minute
    – wishman
    Jun 26, 2015 at 6:28
3

Put (?i) in the replaceAll method's regular expression:

String finalString = DeleteLine.replaceAll("(?i)" + Checkout, "");
1
  • 4
    It's probably worth using Pattern.quote with Checkout as well, otherwise it won't mean what the OP really wants it to.
    – Jon Skeet
    Jun 26, 2015 at 6:21
2

You can do this:

String Checkout = "D:\\\\ifs\\\\APP\\\\Checkout";
String DeleteLine = "D:\\IFS\\APP\\Checkout\\trvexp\\client\\Ifs.App\\text.txt";
String f = DeleteLine.replaceFirst("(?i)"+Checkout, "");
2

Alternatively, if youi want the pattern on a specific portion you can do it manually. You can declare the checkout Sting as:

String Checkout= \Q(?i)D:\ifs\APP\Checkout\E

as

\Q means "start of literal text"
\E means"end of literal text"

and then do the replace

String final = DeleteLine.replace(Checkout, "");

Not the answer you're looking for? Browse other questions tagged or ask your own question.