How to capture a word between two hyphens in python with regex?

Viewed 399

I would like to extract words that are between two hyphens or between one hyphen and nothing. But let's say I am not supposed to know the words before/between/after the hyphens. I've tried with re.search using regex pattern. When using website to test regex the captured groups are not the same in python.

Example :

df = pd.DataFrame({'col1': ['tumPar-PredCorr', 'lung-Med-Pred', 'liver-t1flair-FromMed', 'kidney-t1ce-Pred', 'tumMed-Pred']})

The result in a new column should be : PredCorr, Med, t1flair, t1ce, Pred

With the following code in python :


def extract_signals(row):
    if row!="":
        return re.search(r"([-^]\w+)",row).group()

df["signals"]= df["col1"].apply(extract_signals)

I get almost the result because I have -PredCorr, -Med, -t1flair, -t1ce, -Pred So it would be great to not have the hyphen before those words. Note that those patterns for regex give the same results in python too : ([-]\w+) or (-\w+)

Thank you very much !

1 Answers

You can use

df['signals'] = df['col1'].str.extract(r'-([^-]+)(?:-|$)')

See the regex demo. The regex matches

  • - - a hyphen
  • ([^-]+) - Group 1: one or more chars other than -
  • (?:-|$) - either a - or end of string.

Python test:

>>> import pandas as pd
>>> df = pd.DataFrame({'col1': ['tumPar-PredCorr', 'lung-Med-Pred', 'liver-t1flair-FromMed', 'kidney-t1ce-Pred', 'tumMed-Pred']})
>>> df['col1'].str.extract(r'-([^-]+)(?:-|$)')
          0
0  PredCorr
1       Med
2   t1flair
3      t1ce
4      Pred
Related