How to get the string after last comma in java?

后端 未结 9 699
谎友^
谎友^ 2020-12-18 18:14

How do I get the content after the last comma in a string using a regular expression?

Example:

abcd,fg;ijkl, cas

The output should

相关标签:
9条回答
  • 2020-12-18 18:21

    Only one space:

    String[] aux = theInputString.split(",\\s");
    string result = aux[aux.length-1];
    

    0 to n spaces:

    String[] aux = theInputString.split(",\\s*");
    string result = aux[aux.length-1];
    
    0 讨论(0)
  • 2020-12-18 18:26

    Perhaps something like:

    String s = "abcd,fg;ijkl, cas";
    String result = s.substring(s.lastIndexOf(',') + 1).trim();
    

    That is, I take the substring occurring after the last comma and remove surrounding white space afterwards...

    0 讨论(0)
  • 2020-12-18 18:36

    Using regular expressions:

    Pattern p = Pattern.compile(".*,\\s*(.*)");
    Matcher m = p.matcher("abcd,fg;ijkl, cas");
    
    if (m.find())
        System.out.println(m.group(1));
    

    Outputs:

    cas
    

    Or you can use simple String methods:

    1. System.out.println(s.substring(s.lastIndexOf(",") + 1).trim());
    2. System.out.println(s.substring(s.lastIndexOf(", ") + 2));
    0 讨论(0)
  • 2020-12-18 18:37

    Always think of looking for the answer for this sort of question in Apache Commons... the basic ones should probably be included with most builds. The most appropriate (not using regexes) is this:

    StringUtils.substringAfterLast(String str, String separator)
    

    But if you really want to use a regex for some reason there are a couple of methods which you might want to use, e.g.

    String removeAll(String text, String regex)
    

    or

    String removeFirst(String text, String regex)
    

    Amusingly, you can get what you want by doing this (relying on greedy quantifiers):

    StringUtils.removeFirst( myString, ".*," );
    

    StringUtils is part of apache commons-lang3.

    Apart from anything else there is no point re-inventing the wheel. But I can think of at least 2 other advantages:

    1. the Apache people can also be counted on to have developed well tested code dealing with many "gotchas".
    2. these Apache methods are usually well named: you don't have to clutter up your code with stoopid utility methods; instead you have a nice clean method which does what it says on the tin...

    PS there's nothing to prevent you looking at the source code to check about what the method actually does. Usually they are very easy to understand.

    0 讨论(0)
  • 2020-12-18 18:37

    What about the following:

    String a = "abcd,fg;ijkl, cas";
    String[] result = a.split(",[ ]*");
    String expectedResult = result[result.length - 1]);
    
    0 讨论(0)
  • 2020-12-18 18:37
    str.split(",");
    

    then

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