Reputation: 1101
After runing this
Names.replaceAll("^(\\w)\\w+", "$1.")
I have a String Like
Names = F.DA, ABC, EFG
I want a String format like
F.DA, A.BC & E.FG
How do I do that ?
Update :
If I had a name Like
Robert Filip, Robert Morris, Cirstian Jed
I want like
R.Filp, R.Morris & C.Jed
I will be happy, If also you suggest me a good resource on JAVA Regex.
Upvotes: 2
Views: 152
Reputation: 784878
Following should work for you:
String names = "Robert Filip, Robert Morris, Cirstian Jed, S.Smith";
String repl = names.replaceAll("((?:^|[^A-Z.])[A-Z])[a-z]*\\s(?=[A-Z])", "$1.")
.replaceAll(", (?=[^,]*$)", " & ");
System.out.println(repl); //=> R.Filip, R.Morris, C.Jed & S.Smith
Explanation:
replaceAll
call is matching a non-word && non-dot character + a capital letter in group #1 + 0 or more lower case letters + a space which should be followed by 1 capital letter. It is then inserting a dot in front of the match $1.
replaceAll
call is matching a comma that is not followed by another comma and replacing that by literal string " & "
.Upvotes: 2
Reputation: 6527
Try this
String names = "Amal.PM , Rakesh.KR , Ajith.N";
names = names.replaceAll(" , (?=[^,]*$)", " & ");
System.out.println("New String : "+names);
Upvotes: 0
Reputation: 213193
You need to re-assign the result back to Names
, since Strings are immutable, the replaceAll
methods does not do in place replacement, rather it returns a new String:
names = names.replaceAll(", (?=[^,]*$)", " & ")
Upvotes: 6