Search code examples
regexpython-3.xtext-parsing

Regex solution to {First_name and First_name Last_name} pattern:


This following, I presume, applies regex as used in Python. If there's another way to do this outside of regex, I'm open to that.

I'm need to turn a string of this format:

'{First_name1} and {First_name2 Last_name}'

    (i.e. John and Mary Jones)

to:

'{First_name1 Last_name2}, {First_name2 Last_name2} 

    (i.e. John Jones, Mary Jones)

Being new to regex, this is one pattern that has stumped me. I assume that I'll have to find instances of the entire segment, capture the last name, and use .sub() to add a copy in the right place?

EDIT : While the solutions presented so far do answer the question, I thought I'd mention I found another situation that's being caught by the solutions so far. That is the following:

{First_name1 Last_name1, and First_name2, Last_name2}

Apologies for not having seen (and thus, written in my original question) this pattern before.

So far, I've modified one of the answer to get this far:

([^,]+)(?!\W,)( and [^ ]+ )([^ ]+)

I thought I'd filter based on that comma in this last example. My thinking is that if the comma is present, then I want to move on to the next case. Does that make sense?


Solution

  • With help from @MonkeyZeus, this did the trick:

    (?!\s)(\W[^\W,]+)(?!,)( and [^ ]+ )([^ ]+)