Replace Upper Case in a string With Underscores using regular expression - Java java.lang

Java examples for java.lang:String Case

Description

Replace Upper Case in a string With Underscores using regular expression

Demo Code


//package com.java2s;

import java.util.regex.Pattern;

public class Main {
    public static void main(String[] argv) {
        String name = "java2s.com";
        System.out.println(toUpperCaseWithUnderscores(name));
    }/*from   ww  w.java 2s.c  om*/

    private static final Pattern MAJ_PATTERN = Pattern.compile("([A-Z]+)");
    private static final Pattern NUMBER_PATTERN = Pattern
            .compile("([0-9]+)");

    public static String toUpperCaseWithUnderscores(String name) {
        if (name.length() == 0) {
            return "";
        }
        String result = MAJ_PATTERN.matcher(name).replaceAll("_$1")
                .toUpperCase();
        result = NUMBER_PATTERN.matcher(result).replaceAll("_$1")
                .toUpperCase();
        result = result.replaceAll("_+", "_");
        if (!name.startsWith("_") && result.startsWith("_")) {
            result = result.substring(1);
        }
        return result;
    }
}

Related Tutorials