Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace text within a string

I want to find a text within the string and replace it but it's not working my code. I have to mention that i get normally the Title of the webview, but when i output the text2 i get the whole title (does not replace the text). Also all strings except from text2 , located within a void.

String text1 = web1.getTitle();
String text2 = text1.toString().replace("-Click 2U - Files", "");

Thank you in advance....

like image 918
Jessy Jameson Avatar asked Oct 11 '25 17:10

Jessy Jameson


1 Answers

Your code works for me:

 String text1 = "some string with -Click 2U - Files in it";
 String text2 = text1.replace("-Click 2U - Files", "");
 // here text2.equals("some string with  in it")

This will remove all instances of the string. You can also use replaceAll(...) which uses regular expressions:

 String text1 = "some Click 2U title for Clicking away";
 String text2 = text1.replaceAll("C.*?k", "XXX");
 // here text2.equals("some [XXX 2U title for XXXing away")

Notice that the "C.*?k"pattern will match a C and then any number of characters and then k. The ? means don't do an eager match and stop at the first k. Read your regex manuals for more details there.