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

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

例:

abcd,fg;ijkl, cas 

输出应该是cas


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

使用正则表达式:

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

输出:

 cas 

或者您可以使用简单的String方法:

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

也许是这样的:

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

也就是说,我将最后一个逗号后面的子字符串删除,然后移除周围的空白区域……

你应该总是在Apache Commons中寻找这类问题的答案……每个构建都应该包含基本的问题。 最合适的(不使用正则表达式)是这样的:

 StringUtils.substringAfterLast(String str, String separator) 

但是如果你真的想因某种原因使用正则表达式,你可能想要使用几种方法,例如

 String removeAll(String text, String regex) 

要么

 String removeFirst(String text, String regex) 

有趣的是,你可以通过这样做得到你想要的东西(依靠贪婪的量词):

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

StringUtils是apache commons-lang3的一部分。

除了其他任何事情之外,没有必要重新发明轮子。 但我可以想到至少2个其他优点:

  1. 多年来,阿帕奇人也可以指望预期最多的“陷阱”。 这让你继续,嗯,有趣的东西。
  2. 这些Apache方法通常命名良好:您不必使用stoopid实用程序方法来混淆代码; 相反,你有一个很好的清洁方法,它在锡上做了它所说的……

PS没有什么可以阻止你查看源代码来检查方法实际上做了什么。 通常他们很容易理解。

你可以试试这个:

 public static void main(String[] args) { String s = " abcd,fg;ijkl, cas"; String[] words = s.split(","); System.out.println(words[words.length-1].trim()); } 

只有一个空间:

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

0到n个空格:

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

还有一个:)

 String s = "abcd,fg;ijkl, cas"; String result = s.replaceAll(".*, ", ""); 

以下内容如何:

 String a = "abcd,fg;ijkl, cas"; String[] result = a.split(",[ ]*"); String expectedResult = result[result.length - 1]); 
 str.split(","); 

然后

 str.trim()