match Camel Case using regex - Java java.lang

Java examples for java.lang:String Camel Case

Introduction

The following code shows how to match Camel Case

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String query = "java2s.com";
        String str = "java2s.com";
        System.out.println(matchCamelCase(query, str));
    }/*from   w  w w  .jav a 2  s .  c o m*/

    public static String matchCamelCase(String query, String str) {
        if (!query.matches("[A-Za-z\\*]+")) {
            return null;
        }
        String head = "";
        int i;
        for (i = 0; i < query.length(); i++) {
            char charI = query.charAt(i);
            if (Character.isLowerCase(charI)) {
                head += charI;
            } else {
                break;
            }
        }
        if (i > 0) {
            head += "[^A-Z]*";
        }
        String tail = query.substring(i);
        String re = "\\b(";
        tail = tail.replaceAll("\\*", ".*?");
        re += head + tail.replaceAll("([A-Z][^A-Z]*)", "$1[^A-Z]*");
        re += ".*?)\\b";
        java.util.regex.Pattern regex = java.util.regex.Pattern.compile(re);
        java.util.regex.Matcher m = regex.matcher(str);
        if (m.find()) {
            return m.group();
        } else {
            return null;
        }
    }
}

Related Tutorials