Java RegionMatches Example

0

Consider a user object with fields like name, password etc. Once we have the user object ready its important to make validate the object to make sure the field have proper data. If not the validation engine will log errors for each field. Suppose you want to know whether a specific the user objects has any validation errors, you can use String‘s regionMatches() method to search for errors related to the field.

Using regionMatches() we can compare if two string regions are equal.

Let’s see couple of examples.

Java RegionMatches Example

Spring has two overloaded regionMatches() methods.

  1. regionMatches(start, matchingStr, matchStartOffset, matchLen) – This tests if two string regions are equal. If equal it returns true. A substring of the current string object is compared to a substring of the string passed in as argument. start is the starting offset of the current String object whereas matchStartOffset is the starting offset of the subregion in the string argument. matchLen is the number of characters to compare.
  2. The overloaded method is same as the previous method, but with the additional first argument, which ignores the case differences.

RegionMatchesExample:

package com.javarticles.strings;

import java.io.IOException;

public class RegionMatchesExample {
    public static void main(String[] args) throws IOException {
        String allFields = "user.*";
        String fieldError = "Invalid ${user.name} '*?$'"; 
        
        int startIndex = fieldError.indexOf("${");
        System.out.println("User object has errors? " + allFields.regionMatches(0, fieldError, startIndex + 2, allFields.length() -1));
    }      
}

Output:

User object has errors? true

Case-insensitive RegionMatches Method

In this example, we use the overloaded regionMatches() method which takes in additional argument. We pass in true as we want the string comparison to be case-insensitive.

RegionMatchesExample:

package com.javarticles.strings;

import java.io.IOException;

public class RegionMatchesExample {
    public static void main(String[] args) throws IOException {
        String allFields = "user.*";
        String fieldError = "Invalid ${user.name} '*?$'"; 
        
        int startIndex = fieldError.indexOf("${");
        System.out.println("User object has errors? " + allFields.regionMatches(0, fieldError, startIndex + 2, allFields.length() -1));
        
        allFields = "User.*";
        fieldError = "Invalid ${USER.name} '*?$'"; 
        
        System.out.println("Verify if User.* fields have any error");
        System.out.println("User object has errors? " + allFields.regionMatches(true, 0, fieldError, startIndex + 2, allFields.length() -1));
    }      
}

Output:

User object has errors? true
Verify if User.* fields have any error
User object has errors? true

Find Field Errors using String RegionMatch

In this example, we create a FieldErros object which is a POJO containing the field IDs and the errors in a map member. In findErrors(field), we find the errors related to the field passed in. We use the regionMatches() to compare the field IDs.

FieldErrors:

package com.javarticles.strings;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class FieldErrors {
    private Map<String, String> errors = new HashMap<String, String>();
    
    public void add(String field, String error) {
        errors.put(field, error);
    }

    public List findErrors(String field) {
        int len = field.length() - 1;
        Set errorFields = errors.keySet();
        List errorList = new ArrayList();
        for (String errorField : errorFields) {
            if (field.regionMatches(true, 0, errorField, 0, len)) {
                errorList.add(errors.get(errorField));
            }
        }
        return errorList;
    }
}

FieldErrorsMatcherExample:

package com.javarticles.strings;

import java.io.IOException;

public class FieldErrorsMatcherExample {
    public static void main(String[] args) throws IOException {
        FieldErrors errors = new FieldErrors();
        errors.add("user.name", "Invalid name '*?$'");
        errors.add("USER.password", "Password length should be more than 7 chars");
               
        System.out.println(errors.findErrors("User.*")); 
    }  
}

Output:

[Password length should be more than 7 chars, Invalid name '*?$']

Download the source code

This was an example about Java String.regionMatches Method.

You can download the source code here: javaRegionMatchesExample.zip

About Author

Ram's expertise lies in test driven development and re-factoring. He is passionate about open source technologies and loves blogging on various java and open-source technologies like spring. You can reach him at [email protected]

Comments are closed.