I have recently completed the following programming exercise: Acronym Generator
The statement is:
In nearly every company each employee has a certain acronym containing the first characters of his first and last name(s).
Your task is to write an acronym generator which generates an acronym for a given name. You don't have to care about duplicate acronyms (someone else will do this for you). Note that names can be given in upper or in lower case. The acronym shall always be upper case.
Normally the acronym is always the first letter of your first and the first letter of the last name in upper case.
For example:
Thomas Meyer => TM martin schmidt => MS
In your company there work only people with a maxinmum of two first names. If a person has two first names, they might be joined with a dash.
Jan-Erich Schmidt => JES Jan Erich Mueller => JEM
Last names may also be joined with a dash. No one can have more than two last names.
Paul Meyer-Schmidt
In Germany, there are last names which have the leading word "von". This shall be abbreviated with a lower case "v":
Paul von Lahnstein => PvL Martin von Lahnstein-Meyer => MvLM
I have completed the exercise and I am trying to understand other people's answers. I have found one which uses replaceAll and regex. You can see this solution in this link.
public class AcronymGenerator {
public static String createAcronym(String lastName, String firstName) {
firstName = firstName.toUpperCase().replaceAll("(.)([A-Z])*([-| ])?(.)?(.)*", "$1$4");
String von = lastName.toLowerCase().replaceAll("^((v)(on ))?(.)*", "$2");
lastName = lastName.toUpperCase().replaceAll("(VON )?(.)([A-Z])*([-| ])?(.)?(.)*", "$2$5");
return firstName+von+lastName;
}
}
I guess what he does is replace names by their initial in capital letters, von by the v, and surnames by their initial in capital letters. However, I do not understand how the groups of regular expressions work when used within replaceAll
Could you explain how replaceAll() works with regex groups? I would like to understand how it works:
replaceAll("(.)([A-Z])*([-| ])?(.)?(.)*", "$1$4");
replaceAll("^((v)(on ))?(.)*", "$2");
replaceAll("(VON )?(.)([A-Z])*([-| ])?(.)?(.)*", "$2$5");
I have also read: Java: Understanding the String replaceAll() method What is a non-capturing group in regular expressions? How to Extract people's last name start with "S" and first name not start with "S"