[SOLVED] Replacing element inside a Collection by using regular expressions


I have a Collection of strings.

I need to replace some characters with given relevant characters.

I was tried this. But my code but doesn’t work correctly.

public class MyPattern {
    public static void main(String[] args)
        String items;
        Collection<String> arr = new ArrayList<String>();
        arr.add("I00.30");  //Expected output: 100.30
        arr.add("8B4.99");  //Expected output: 884.99
        arr.add("B37.2B");  //Expected output: 837.28
        arr.add("292.b4");  //Expected output: 262.64
        arr.add("24|.7O");  //Expected output: 241.70
        arr.add("B55.I4");  //Expected output: 855.14
        arr.add("444.07");  //Expected output: 444.07

        for(String item:arr)
            items = item.toUpperCase().replaceAll("l", "1")
                .replaceAll("l", "1")
                .replaceAll("i", "1")
                .replaceAll("|", "1")
                .replaceAll("G", "6")
                .replaceAll("b", "6")
                .replaceAll("B", "8")
                .replaceAll("O", "0");

The letters passed in the replaceAll() method has to be replaced in every item in the collection.

Is there any way to find the irrelevant character and replace it with the number (as shown in the code above) ?


Your code is resigning the variable item, it will not affect the list contents.

To be able to do that, you might change the type of variable arr to List. With that, you can iterate over it by using the traditional (index based) for loop.

List<String> arr = // initializing the list

for (int i = 0; i < arr.size(); i++) {
    String item = replace(arr.get(i)); // method replace provided below
    arr.set(i, item);

Another option is to use Java 8 replaceAll() method, which expects a function that will be applied to every element in the collection.

arr.replaceAll(str -> replace(str));
public static String replace(String source) {
    return source.toUpperCase()
            .replaceAll("[LI|]", "1")
            .replaceAll("[GB]", "6")
            .replace("O", "0");

Note that method replaceAll() that expect a regular expression is more expensive than replace(). Hence, when you don’t need a regex, its better to use any flavor of replace() (with either char or String arguments).

Here you can benefit from replaceAll() by processing characters L, L and | in one go with a regular expression "[LI|]".

For more information on regular expressions take a look at this tutorial

There’s also a minor issue in your code:

  • After toUpperCase() has been applied, it doesn’t make sense to try to replace lowercase letters like ‘l’ or ‘i’.
  • There’s a clash "b", "6" and "B", "8".

I hope with all these hints you’ll be able to manage to get it working.

Answered By – Alexander Ivanchenko

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *