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
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];
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...
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:
System.out.println(s.substring(s.lastIndexOf(",") + 1).trim());
System.out.println(s.substring(s.lastIndexOf(", ") + 2));
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:
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.
What about the following:
String a = "abcd,fg;ijkl, cas";
String[] result = a.split(",[ ]*");
String expectedResult = result[result.length - 1]);
str.split(",");
then
str.trim()