Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Get first character values for a string

I have inputs like

AS23456SDE

MFD324FR

I need to get First Character values like

AS, MFD

There should no first two or first 3 characters input can be changed. Need to get first characters before a number.

Thank you.

Edit : This is what I have tried.

public static String getPrefix(String serial) {
    StringBuilder prefix = new StringBuilder();
        for(char c : serial.toCharArray()){
            if(Character.isDigit(c)){
                break;
            }
            else{
                prefix.append(c);
            }
        }
        return prefix.toString();
}
like image 837
user2473015 Avatar asked Nov 29 '25 03:11

user2473015


1 Answers

Here is a nice one line solution. It uses a regex to match the first non numeric characters in the string, and then replaces the input string with this match.

public String getFirstLetters(String input) {
    return new String("A" + input).replaceAll("^([^\\d]+)(.*)$", "$1")
                                  .substring(1);
}

System.out.println(getFirstLetters("AS23456SDE"));
System.out.println(getFirstLetters("1AS123"));

Output:

AS
(empty)
like image 128
Tim Biegeleisen Avatar answered Dec 01 '25 15:12

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!