Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replaceFirst does not work, but replace works on the exact same input?

Tags:

java

string

regex

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!

like image 732
Jeremy Avatar asked Dec 04 '22 11:12

Jeremy


2 Answers

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.

like image 133
gkalpak Avatar answered Jan 11 '23 08:01

gkalpak


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
like image 29
Eng.Fouad Avatar answered Jan 11 '23 10:01

Eng.Fouad