GobiasKoffi
GobiasKoffi

Reputation: 4084

Add separator in string using regex in Java

I have a string (for example: "foo12"), and I want to add a delimiting character in between the letters and numbers (e.g. "foo|12"). However, I can't seem to figure out what the appropriate code is for doing this in Java. Should I use a regex + replace or do I need to use a matcher?

Upvotes: 0

Views: 845

Answers (3)

Justin
Justin

Reputation: 25287

Why even use regex? This isn't too hard to implement on your own:

public static String addDelimiter(String str, char delimiter) {
    StringBuilder string = new StringBuilder(str);
    boolean isLetter = false;
    boolean isNumber = false;

    for (int index = 0; index < string.length(); index++) {
        isNumber = isNumber(string.charAt(index));
        if (isLetter && isNumber) {
            //the last char was a letter, and now we have a number
            //so here we adjust the stringbuilder
            string.insert(index, delimiter);
            index++; //We just inserted the delimiter, get past the delimiter
        }
        isLetter = isLetter(string.charAt(index));
    }
    return string.toString();
}
public static boolean isLetter(char c) {
    return 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z';
}
public static boolean isNumber(char c) {
    return '0' <= c && c <= '9';
}

The advantage of this over regex is that regex can easily be slower. Additionally, it is easy to change the isLetter and isNumber methods to allow for inserting the delimiter in different places.

Upvotes: 0

gkrls
gkrls

Reputation: 2664

Split letters and numbers and concatenate with "|". Here is a one-liner:

String x = "foo12";

String result = x.replaceAll("[0-9]", "") + "|" + x.replaceAll("[a-zA-Z]", "");

Printing result will output: foo|12

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

A regex replace would be just fine:

 String result = subject.replaceAll("(?<=\\p{L})(?=\\p{N})", "|");

This looks for a position right after a letter and right before a digit (by using lookaround assertions). If you only want to look for ASCII letters/digits, use

String result = subject.replaceAll("(?i)(?<=[a-z])(?=[0-9])", "|");

Upvotes: 4

Related Questions