4

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....

8
  • 2
    It's a very simple google: daniweb.com/software-development/java/threads/73139 Commented Mar 6, 2012 at 19:48
  • Can you provide the full title and the actual replacement you are using? Commented Mar 6, 2012 at 19:49
  • My guesse would be that your search string gets interpreted as a regex, and you think it is handled as a regular string ? Commented Mar 6, 2012 at 19:51
  • 5
    why do you call toString() on a String? Commented Mar 6, 2012 at 19:52
  • @C.d. i was checking if bugs for that.... this is not the problem.... Commented Mar 6, 2012 at 19:57

2 Answers 2

13

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.

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

2 Comments

i didn't understand how to use this code ..what does this code assertEquals("some string with in it", text2); ? thank you
Sorry, that's just showing you what the output would be. I'll edit my answer to make that more plain.
0

I used it for replace password

input

{"Login":"login1", "Password":"password1"} 

inputParameters.toString().replaceAll( "(\"Password\":\")+\\w+\"", "\"Password\":\"*********\"") + "\"")

output

{"Login":"login1", "Password":"*********"}

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.