match Camel Case using regular expression - Java java.lang

Java examples for java.lang:String Camel Case

Description

match Camel Case using regular expression

Demo Code

//package com.java2s;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] argv) {
        String query = "java2s.com";
        String str = "java2s.com";
        System.out.println(matchCamelCase(query, str));
    }// ww w  .  j a  v  a 2  s  .  c  om

    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";
        Pattern regex = Pattern.compile(re);
        Matcher m = regex.matcher(str);
        if (m.find()) {
            return m.group();
        } else {
            return null;
        }
    }
}

Related Tutorials