Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get String between last two underscore

Tags:

java

regex

I have a string "abcde-abc-db-tada_x12.12_999ZZZ_121121.333"

The result I want should be 999ZZZ

I have tried using:

private static String getValue(String myString) {
    
    Pattern p = Pattern.compile("_(\\d+)_1");
    Matcher m = p.matcher(myString);
    if (m.matches()) {
        System.out.println(m.group(1));  // Should print 999ZZZ
    }
    else {
         System.out.println("not found"); 
    }
}
like image 556
RishiKesh Pathak Avatar asked Jun 15 '26 17:06

RishiKesh Pathak


2 Answers

If you want to continue with a regex based approach, then use the following pattern:

.*_([^_]+)_.*

This will greedily consume up to and including the second to last underscrore. Then it will consume and capture 9999ZZZ.

Code sample:

String name = "abcde-abc-db-tada_x12.12_999ZZZ_121121.333";
Pattern p = Pattern.compile(".*_([^_]+)_.*");
Matcher m = p.matcher(name);
if (m.matches()) {

    System.out.println(m.group(1));  // Should print 999ZZZ

} else {
     System.out.println("not found"); 
}

Demo

like image 147
Tim Biegeleisen Avatar answered Jun 17 '26 05:06

Tim Biegeleisen


Using String.split?

String given = "abcde-abc-db-tada_x12.12_999ZZZ_121121.333";
String [] splitted = given.split("_");
String result = splitted[splitted.length-2];
System.out.println(result);
like image 33
johnII Avatar answered Jun 17 '26 06:06

johnII