如何在java中的最后一个逗号后获取字符串?

问题描述:

如何使用正则表达式获取字符串中最后一个逗号后的内容?

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

示例:

abcd,fg;ijkl, cas

输出应为 cas

注意:最后一个之间有空格逗号和'c'字符也需要删除。
此模式在最后一个逗号后只包含一个空格。

Note: There is a space between last comma and 'c' character which also needs to be removed. Also the pattern contains only one space after last comma.

使用正则表达式:

Pattern p = Pattern.compile(".*,\\s*(.*)");
Matcher m = p.matcher("abcd,fg;ijkl, cas");

if (m.find())
    System.out.println(m.group(1));

输出:

cas






或者你可以使用简单字符串方法:


  1. System.out.println (s.substring(s.slastIndexOf(,)+ 1).trim());

  2. System.out。 println(s.substring(s.lastIndexOf(,)+ 2));

  1. System.out.println(s.substring(s.lastIndexOf(",") + 1).trim());
  2. System.out.println(s.substring(s.lastIndexOf(", ") + 2));