如何在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
或者你可以使用简单字符串
方法:
-
System.out.println (s.substring(s.slastIndexOf(,)+ 1).trim());
-
System.out。 println(s.substring(s.lastIndexOf(,)+ 2));
System.out.println(s.substring(s.lastIndexOf(",") + 1).trim());
System.out.println(s.substring(s.lastIndexOf(", ") + 2));