如何在最后两个下划线之间获取字符串 [英] How to get String between last two underscore

查看:84
本文介绍了如何在最后两个下划线之间获取字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串"abcde-abc-db-tada_x12.12_999ZZZ_121121.333"

结果为 999ZZZ

我尝试使用

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"); 
    }
}

推荐答案

如果要继续使用基于正则表达式的方法,请使用以下模式:

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

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

这将贪婪地消耗掉并包括倒数第二个下层幕.然后它将消耗并捕获 9999ZZZ .

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

代码示例:

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"); 
}

演示

这篇关于如何在最后两个下划线之间获取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆