替换字符串中的文本 [英] replace text within a string
问题描述
我想在字符串中找到一个文本并替换它,但它不能处理我的代码。我必须提到我通常会获得webview的标题,但是当我输出 text2
时,我得到整个标题(不替换文本)。此外所有字符串除了 text2
之外,位于void内。
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", "");
提前谢谢....
推荐答案
您的代码适合我:
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")
这将是删除字符串的所有实例。您还可以使用 replaceAll(...)
使用正则表达式:
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")
请注意,C。*?k
模式将匹配 C
然后匹配任意数量的字符然后ķ
。 ?
表示不进行急切匹配并在第一个 k
处停止。阅读您的正则表达式手册更多细节。
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.
这篇关于替换字符串中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!