Brad
Brad

Reputation: 71

Reorder string contents delimited by semicolon using Regex?

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

Answers (2)

Andrew Cheong
Andrew Cheong

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

mishik
mishik

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

Related Questions