How to get the string after last comma in java?

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

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...

Tags:

Java

Regex