[英]Delete all from string except a special word
Let's say I have a string like this: 假设我有一个像这样的字符串:
String test = "hfikoebndolahsdHEL123LOkjahhsdqhuihs";
And then I want to delete all except the "HEL123LO" BUT the number could be like 653 and it wont delete it anyway. 然后,我想删除除“ HEL123LO”以外的所有内容,但该数字可能类似于653,无论如何它都不会删除它。 Is that possible?
那可能吗?
I hope you understand me! 我希望你能理解我!
Thanks in advance. 提前致谢。
(Sorry for bad english). (对不起,英语不好)。
Use the String.replaceAll()
method with the right regex. 将
String.replaceAll()
方法与正确的正则表达式一起使用。
test = test.replaceAll(".*(HEL\\d{3}LO).*", "$1");
This regex matches the whole input and replaces it with the matched group (group number 1). 此正则表达式匹配整个输入,并将其替换为匹配的组(组号1)。
If your String
is going to be of the kinds that you have mentioned, "hfikoebndolahsdHEL123LOkjahhsdqhuihs"
with the likes of just the number changes in between, and you want to retain HEL123LO
and rest of the letters are of the kind like in your example, you could do a simple substring. 如果您的
String
将是您提到的那种类型, "hfikoebndolahsdHEL123LOkjahhsdqhuihs"
之间只是数字变化,并且您想保留HEL123LO
,其余字母就是您示例中的那种可以做一个简单的子字符串。 I know this may not be the best solution, but just suggesting an alternative. 我知道这可能不是最好的解决方案,而只是提出了一种替代方案。
test = test.substring(test.indexOf("H"),(test.lastIndexOf("O")+1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.