[英]How to extract a specific substring in Java
I have a string that I define as 我有一个定义为的字符串
String string = "<html><color=black><b><center>Line1</center><center>Line2</center></b></font></html>";
that I apply to a JButton to get 2 lines of text on it, and that works perfectly. 我将其应用于JButton以获得2行文本,并且效果很好。 When I call the JButton.getText() method, it returns the whole string. 当我调用JButton.getText()方法时,它将返回整个字符串。 What I want is to take the string it returns, and get the string "Line1Line2" from it. 我想要的是获取它返回的字符串,并从中获取字符串“ Line1Line2”。 (So I want to remove all the HTML code and just get the text that appears on the screen.) I have tried using something like (因此,我想删除所有HTML代码,只获取显示在屏幕上的文本。)我尝试使用类似
if(string.contains("<html>"))
{
string.replace("<html>", "");
}
and then doing the same thing for all the other "<(stuff)>", but if I then print the string, I still get the whole thing. 然后对所有其他“ <(stuff)>”执行相同的操作,但是如果我随后打印字符串,我仍然会得到整个结果。 I think using regular expressions is a better way than to manually remove all the "<(stuff)>", but I don't know how. 我认为使用正则表达式是比手动删除所有“ <(stuff)>”更好的方法,但是我不知道如何。
Any help would be most appreciated! 非常感激任何的帮助!
string.replace()
doesn't modify the string: a String is immutable. string.replace()
不会修改字符串:字符串是不可变的。 It returns a new string where the replacement has been done. 它返回完成替换的新字符串。
So your code should be 所以你的代码应该是
if (string.contains("<html>")) {
string = string.replace("<html>", "");
}
String
is immutable, so String#replace
does not change the String
but rather returns the changed String
. String
是不可变的,因此String#replace
不会更改String
而是返回更改后的String
。
string = string.replace("<html>", "");
and so on should do the thing. 等等应该做的事情。
String
also has a replaceAll()
method. String
还具有replaceAll()
方法。
you could try string.replaceAll("<.*?>", "");
您可以尝试string.replaceAll("<.*?>", "");
Also keep in mind that Strings in java are immutable and this operation will return a new String with your result 另外请记住,java中的字符串是不可变的,此操作将返回带有结果的新字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.