替换字符串中的文本 [英] replace text within a string

查看:82
本文介绍了替换字符串中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在字符串中找到一个文本并替换它,但它不能处理我的代码。我必须提到我通常会获得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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆