Reputation: 3198
I need to extract the middle and last names
Elev: 7EBB49 (Dan Greg Järgenstedt <[email protected]>)
Expected: Greg Järgenstedt
Elev: 6EBB49 (Dan Järgenstedt <[email protected]>)
Expected: Järgenstedt
Elev: 6EBB49 (Järgenstedt <[email protected]>)
Expected: Järgenstedt
Elev: 6EBB49 (<[email protected]>)
Expected:
Tried with
function getSNames(input) {
const names = input.match(/(?<!\[)(?<=\s)\w+(?=\s)/g);
return names ? names.join(' ') : '';
}
Upvotes: 3
Views: 243
Reputation: 15907
This way madness lies.
I don't think you can "extract the middle and last names" in general. If all you have is "Name", then you're stuck with it. Whatever rule you come up with, I'll show you a person where it doesn't work. E.g.
What you're doing won't work in the general case, especially not internationally.
Upvotes: 1
Reputation: 626747
You can use
const names = input.match(/(?<!\(\p{L}+\s+|\p{L})\p{L}+(?:\s+\p{L}+)*(?=\s*<)/gu)
See the regex demo. The u
flag enables the Unicode category classes.
Pattern details
(?<!\(\p{L}+\s+|\p{L})
- immediately to the left, there cannot be a (
followed with 1+ letters and then one or more whitespaces, or just a letter (this works as a Unicode word boundary)\p{L}+
- one or more letters(?:\s+\p{L}+)*
- zero or more occurrences of 1+ whitespaces and then 1+ letters(?=\s*<)
- immediately to the right, there must be 0+ whitespaces and then <
.Upvotes: 2