regex :strange results when using \1

Viewed 81

In order to manage a df, I'm applying df['sum1'] = df['sum'].str.replace(r'.+(.+).+\1', '.+\1', regex=True) in order to eliminate the duplicate of record in "sum"

    sum                                                             sum1      Target
8   Chiaro Gallo (blabla) (blabla)                                  Che)      Chiaro Gallo (blabla)
9   Ricard Michaeln ()                                              Rhan      Ricard Michaeln ()
10  Marco Liu (Hong Kong Stock Co Ltd) Hong Kong Stock Co Ltd       MarkLtd)  Marco Liu (Hong Kong Stock Co Ltd)
15  Rafiq (Kkska Traning Co (p) Ltd) Kkska Traning Co (p) Ltd       RgLtd     Rafiq (Kkska Traning Co (p) Ltd)
    
    ......

.. but I'm obtaining such strange result in "sum1"

1 Answers

You can use

df['Target'] = df['sum'].str.replace(r'\((.*)\).*?\(?\1\)?', r'(\1)', regex=True)

See the regex demo. Details:

  • \( - a ( char
  • (.*) - Group 1: any zero or more chars other than line break chars as many as possible
  • \) - a ) char
  • .*? - any zero or more chars other than line break chars as few as possible
  • \(? - an optional ( char
  • \1 - same value as in Group 1
  • \)? - an optional ) char

To get the sum1 column, you can use the same regex (it can even be a bit shortened) in .str.extract:

df['sum1'] = df['sum'].str.extract(r'\((.*)\).*?\1', expand=False)
Related