Case Insensistive Regular Expressions in Java

Thanks to this post, I’ve discovered how to use case insensitive regular expressions.

Simply start your regular expression with “?i:”.  So “(?i:REGEX)” matches REGEX case insensitively.

In the code example below, one can use this to extract out an attribute value inside quotes when the attribute name is case-insensitive.

public static void main(String[] args) {
        String example = "somePrefix NAME=\"value\" someSuffix";

        Pattern p = Pattern.compile("(.*)\\s(?i:name=)(\"(.*)\")\\s(.*)");
        Matcher m = p.matcher(example);
        if (m.matches()) {

            MatchResult mr = m.toMatchResult();

            for( int i = 0; i <= mr.groupCount(); i++) {
                System.out.println("Group "+i+": "+mr.group(i));
            }
        }

        if ( m.matches() && m.groupCount()>=3) {
            System.out.println("Extracted value: "+m.group(3));
        }

    }

The code output yielded is:

Group 0: somePrefix NAME="value" someSuffix
Group 1: somePrefix
Group 2: "value"
Group 3: value
Group 4: someSuffix
Extracted value: value
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s