Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the string after last comma in java?

Tags:

java

regex

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 be cas


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.

like image 632
Nitish Avatar asked Mar 01 '12 11:03

Nitish


People also ask

How do you find the last comma in a string?

var s = 'test, test, test'; s = s. replace(/,([^,]*)$/, 'and $1'); This will find the last comma in a string and replace it with "and" and anything that came after it.

What comes after last Java?

The substringAfterLast() method is a static method of StringUtils . It is used to return the substring that comes after the last occurrence of the given separator. The separator is not returned along with the substring.

How do you cut a string after a specific character in Java?

Java – Split a String with Specific Character To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.


1 Answers

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));
like image 114
dacwe Avatar answered Sep 20 '22 02:09

dacwe