Regex to find a string after the last colon

后端 未结 4 544
滥情空心
滥情空心 2021-01-28 08:34

Here is some sample input:

<210>   DW_AT_name        : (indirect string, offset: 0x55): double
    DW_AT_name        : (indirect string, offset:          


        
相关标签:
4条回答
  • 2021-01-28 09:08

    This regexp ^.*DW_AT_name.*:\s*(.+)$ does the job as just tested on regexplanet.

    0 讨论(0)
  • 2021-01-28 09:11
    String type = str.replaceAll(".*:(?=[^:]+$)", "");
    
    0 讨论(0)
  • 2021-01-28 09:21

    Try the next:

    public static void main(String[] args) {
    
        String text = 
        "<210>   DW_AT_name        : (indirect string, offset: 0x55): double\n" + 
        "<ae>   DW_AT_name        : (indirect string, offset: 0x24): long int\n" + 
        "<b5>   DW_AT_name        : int";
    
        Pattern pattern = Pattern.compile("^.*DW_AT_NAME.*:\\s*([^:]+)$", 
                Pattern.CASE_INSENSITIVE);
    
        Scanner sc = new Scanner(text);
        while(sc.hasNextLine()) {
            String line = sc.nextLine();
            Matcher matcher = pattern.matcher(line);
            if (matcher.matches()) {
                System.out.println(matcher.replaceAll("$1"));
            }
        }
    
    }
    

    Output:

    double
    long int
    int
    
    0 讨论(0)
  • 2021-01-28 09:30

    You need no regex for this:

    String yourString = "<210>   DW_AT_name        : (indirect string, offset: 0x55): double";
    String result;
    if (yourString.contains("DW_AT_name")) {
        int lastIndex = yourString.lastIndexOf(":");
        result = yourString.substring(lastIndex + 1).trim();
    } else {
        result = "ERROR"; // or handle this however you want
    }
    System.out.println(result);
    

    Simply find the last : and take everything after that. Then trim it to remove leading and trailing whitespace.

    I edited my question, it needs to also check for DW_AT_name. String split wont [sic] do that.

    Just use contains, then. (edited answer)

    0 讨论(0)
提交回复
热议问题