How to remove all strings except the given value

Viewed 78

So my code is: 

String value = "123456" 

I want to remove everything except for 2 and 5. the output will be 25 the program should work even the value is changed for example: 

String value = "463312"

The output will be 2.

I tried replaceAll() but it doesn't work.

2 Answers

It does, just you have to use the right regular expression.

String newValue = value.replaceAll("[^25]", "");

This one says that everything that doesn't (^ stands for the negation) match the items between [ and ] (set of values) will be erased.

Use regex [^25]

String newStr = value.replaceAll("[^25]","");
Related