Abhishek Bhardwaj
Abhishek Bhardwaj

Reputation: 1204

How to split a String from reverse where first character is found in java?

I have a String like MH12PE1433 I am trying to finding a regular expression to split it from the end where I got the first character for eg.

String str1=1433;
String str2=MH12PE;

I am able to split last 4 digits by using

String no=MH12PE1433;
if (no.length() > 3) {
                        text2 = no.substring(no.length() - 4);
}

but want to split using regular expression where the first alphabet is found. I hope you understood my question Thanks

Upvotes: 1

Views: 1136

Answers (3)

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

You can use this regex to split the way you want,

(?<=[A-Z])(?=\d+$)

Here (?<=[A-Z]) positive lookbehind marks the start of first alphabet and (?=\d+$) marks the start of continuous digits till end of string, hence giving you the point inside string you are looking for. Just splitting with that point will give you your desired output.

Java code,

String s = "MH12PE1433";
System.out.println(Arrays.toString(s.split("(?<=[A-Z])(?=\\d+$)")));

Prints,

[MH12PE, 1433]

You can also play with the demo here

Also, in case you have any non-alphabet string and not just numbers at the end of string, you can more generally use this regex, which will split your text from the last alphabet (as you say first alphabet from end of string).

(?<=[A-Za-z])(?=[^A-Za-z]*$)

Java code,

List<String> list = Arrays.asList("MH12PE1433","MH12PE@@1123", "MH12PE@@##$$", "MH12Pe5555");
list.forEach(x -> System.out.println(x + " --> " + Arrays.toString(x.split("(?<=[A-Za-z])(?=[^A-Za-z]*$)"))));

Prints,

MH12PE1433 --> [MH12PE, 1433]
MH12PE@@1123 --> [MH12PE, @@1123]
MH12PE@@##$$ --> [MH12PE, @@##$$]
MH12Pe5555 --> [MH12Pe, 5555]

Upvotes: 5

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

You can use a regex that matches digits [0-9]+ at the end of the string by adding a $ at the end of the regex.

private static final Pattern pattern = Pattern.compile("([0-9]+)$");

private String extractTrailingDigits(String s) {
    Matcher matcher = pattern.matcher(s);
    if (matcher.find()) {
        return matcher.group(1);
    } else {
        return "";
    }
}

private void test() {
    String[] tests = {"MH12PE1433", "MH12PE1433000"};
    for (String test : tests) {
        System.out.println(test + " -> " + extractTrailingDigits(test));
    }
}

Upvotes: 0

akshaya pandey
akshaya pandey

Reputation: 997

You can try following: a. Replace all digits from end using following code to get the earlier string. b. Replace the derived String from original to gets the digits at the end.

String no="MH12PE1433";
    String regex="[0-9]+$";//all ending digits
    String prefix = no.replaceFirst(regex, "");//MH12PE
    String suffix = no.replaceFirst(prefix, "");//1433

Upvotes: 1

Related Questions