简体   繁体   English

从字符串中删除所有字符,但特殊单词除外

[英]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.

相关问题 从字符串中删除所有特殊字符(数字和度数符号除外)? - Remove all special characters from a string except for digits and the degree symbol? 如何从字符串中删除除-以外的所有特殊字符。 和空间 - How to remove all special Characters from a string except - . and space 如何删除字符串中除点和逗号以外的所有特殊字符 - How to remove all special character in a string except dot and comma 如何在除点之外的所有特殊字符处拆分String? - How to split a String at all special characters except dot? 检查字符串的所有字符是否都是大写,除了特殊符号 - Checking if all characters of a string is uppercase except special symbols 是否可以将所有特殊字符和标点符号(除句点)分割成字符串? - Is it possible to split a string by all special characters and punctuation EXCEPT period? 删除java中单词和特殊字符之间的字符串内容 - Delete the content of a string between a word and special character in java 用Java中字符串中的特殊字符替换单词 - Replace word with special characters from string in Java 最简单的方法来获取除字符串中的最后一个单词之外的每个单词 - easiest way to get every word except the last word from a string 从文件行中删除所有特殊字符(空格除外) - Remove all special characters from file line except white space
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM