I am writing a program where a portion of it needs to replace part of the string without deleting duplicates so I am using replaceFirst() which is not working properly.
INPUT:
lock: "O_2_^-^"
str: " O_2_^-^ "
CODE:
System.out.println(str);
System.out.println(lock);
System.out.println(str.contains(lock));
str = str.replaceFirst(lock, "");
System.out.println(str);
OUTPUT:
O_2_^-^
O_2_^-^
true
O_2_^-^
The above is real output from my program. Though the replace() method will not work for my current situation I did test it and the output is compeletely different, as in correct.
INPUT:
lock: "O_2_^-^"
str: " O_2_^-^ "
CODE:
System.out.println(str);
System.out.println(lock);
System.out.println(str.contains(lock));
str = str.replace(lock, "");
System.out.println(str);
OUTPUT:
O_2_^-^
O_2_^-^
true
//empty line of output because string was detected and removed.
I have tried everything outside of writing my own replaceFirst() method, if anyone has any advice or input that'd be great. Thanks!
Since replaceFirst
's 1st parameter is assumed to be a regex, you need to escape special characters. If you do not know beforehand what lock
is going to be (example coming from user-input), you can use Pattern.quote(lock)
to escape it.
See, also, this short demo.
replaceFirst(String regex, String replacement)
takes regex as a parameter, use this:
String lock = "O_2_\\^-\\^";
String lock = "O_2_\\^-\\^";
String str = " O_2_^-^ ";
System.out.println(str);
System.out.println(lock);
System.out.println(str.contains(lock));
str = str.replaceFirst(lock, "");
System.out.println(str);
OUTPUT:
O_2_^-^
O_2_\^-\^
false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With