Reputation: 71
I have a string of names separated by a semicolon delimiter in the format firstname lastname.
i.e.
John Doe; R.J. Smith; Peter T. Thompson; Sabine Geiß
How would one reorder these names as 'lastname, firstname', preferably using RegEx?
Doe, John; Smith, R.J.; Thompson, Peter T.; Geiß, Sabine
Upvotes: 0
Views: 127
Reputation: 30283
Assuming no suffixes are present (i.e. last names are always only the last word), you'd (globally) replace
\s*([^\s;]+(?:\s+[^\s;]+)*)\s+([^\s;]+)\s*(?:;|$)
with
$2, $1
Upvotes: 1
Reputation: 10003
The regex would be:
/\s?([\w.\s]+)\s([\w.]+);/g
This will match first and second word, followed by ;
.
To achieve what you want in (for example) JavaScript:
your_string.replace(/\s?([\w.\s]+)\s([\w.]+);/g, "$2, $1")
Example:
"John Doe; R.J. Smith; Peter T. Thompson; Sabine Geiß".replace(/\s?([\w.\s]+)\s([\w.]+);/g, " $2, $1;")
" Doe, John; Smith, R.J.; Thompson, Peter T.; Sabine Geiß"
Upvotes: 2