Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove characters before a comma in a string

Tags:

java

string

I was wondering what would be the best way to go about removing characters before a comma in a string, as well as removing the comma itself, leaving just the characters after the comma in the string, if the string is represented as 'city,country'.

Thanks in advance

like image 715
user1899174 Avatar asked Apr 29 '13 18:04

user1899174


People also ask

How do I remove text before a comma in Excel?

In the 'Find what' field, enter ,* (i.e., comma followed by an asterisk sign) Leave the 'Replace with' field empty. Click on the Replace All button.


2 Answers

check this

String s="city,country";
System.out.println(s.substring(s.lastIndexOf(',')+1));

I found it faster than .replaceAll(".*,", "")

like image 145
Bassem Reda Zohdy Avatar answered Sep 19 '22 12:09

Bassem Reda Zohdy


So you want

city,country

to become

country

An easy way to do this is this:

public static void main(String[] args) {
    System.out.println("city,country".replaceAll(".*,", ""));
}

This is "greedy" though, meaning it will change

city,state,country

into

country

In your case, you might want it to become

state,country

I couldn't tell from your question.

If you want "non-greedy" matching, use

System.out.println("city,state,country".replaceAll(".*?,", ""));

this will output

state, country

like image 24
Daniel Kaplan Avatar answered Sep 17 '22 12:09

Daniel Kaplan