GuiceU
GuiceU

Reputation: 1038

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. Is that possible?

I hope you understand me!

Thanks in advance.

(Sorry for bad english).

Upvotes: 1

Views: 210

Answers (2)

Kazekage Gaara
Kazekage Gaara

Reputation: 15052

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. I know this may not be the best solution, but just suggesting an alternative.

test = test.substring(test.indexOf("H"),(test.lastIndexOf("O")+1));

Upvotes: 4

Bohemian
Bohemian

Reputation: 425073

Use the String.replaceAll() method with the right regex.

test = test.replaceAll(".*(HEL\\d{3}LO).*", "$1");

This regex matches the whole input and replaces it with the matched group (group number 1).

Upvotes: 14

Related Questions