Reputation: 71
I have one long String that contains the full name of the person and in the parentheses the skill for the person. However, in some cases, the same person has two skills.
For example:
John Adams (Backend developer)
Bob Scott (Frontend developer) (UI/UX designer)
Alex Walker (Network engineer)
Steve Douglas (Backend developer) (Software design)
John Adams (IT coordinator)
The String that I get is the following:
"John Adams (Backend developer) Bob Scott (Frontend developer) (UI/UX designer) Alex Walker (Network engineer) Steve Douglas (Backend developer) (Software design) John Adams (IT coordinator)"
My question is, how do I get each person with the matching skill? And what type of data structure to use?
my program is in Java.
Edit:
What I have done so far:
I've solved the problem when each person has only one job title. Let's say:
String data = "John Adams (Backend developer) Alex Walker (Network engineer)";
By extracting the name of the person using the following regex that returns everything inside parentheses:
\((.*?)\)
and then split the string using that regex I get everyone's names in the list.
String regx = " \((.*?)\)";
List<String> names = Arrays.stream(data.split(regx)).toList();
Then I get the job titles in a separate list in the following way:
List<String> roles = new ArrayList<>();
Matcher matcher = Patter.compile("\((.*?)\)").mathcer(data);
while(mathcer.find()) {
roles.add(mathcer.group);
}
After doing all of the above I have the following situation:
names = {
0: "John Adams"
1: " Alex Walker"
}
roles = {
0: "(Backend developer)"
1: "(Network engineer)"
}
after which I will basically match the person and the skill by the corresponding index from each list.
However, the whole situation changes when there are multiple skills for one person.
Let's say:
String data = "John Adams (Backend developer) Bob Scott (Frontend developer) (UI/UX designer) Alex Walker (Network engineer) "
By applying the above method I end up in this situation:
names = {
0: "John Adams"
1: " Bob Scott"
2: ""
3: " Alex Walker"
}
roles = {
0: "(Backend developer)"
1: "(Frontend developer)"
2: "(UI/UX designer)"
3: "(Network engineer)"
}
In this situation, I am not able to match the persons and the skills using the matching indexes.
Upvotes: 1
Views: 274
Reputation: 425043
Here's a one-liner that creates a Map<String, List<String>>
of each person and their skill(s):
Map<String, List<String>> skills = Pattern.compile("(.*?) \\((.*?)\\)(?! \\() ?")
.matcher(data) // a Matcher object for the input
.results() // stream all MatchResults
.collect(toMap(mr -> mr.group(1), mr -> Arrays.asList(mr.group(2).split("\\) \\("))));
See live java demo.
This streams all matches of (.*?) \\((.*?)\\)(?! \\() ?
, which matches the name as group 1 and the skill(s) as group 2, through to a collector that uses the name (group 1) as the key and converts the skills to a List<String>
via a split on ") ("
.
Also see live regex demo of the name-skills pair match.
Upvotes: 2