Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract string/characters before a number using regex

I would like to extract everything that comes before a number using regex.

The dataframe below shows an example of what I want to do.

I want to extract everything that comes before the first number in the product_name column. The output column is what I want to get.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you in advance!

product_name = ['Cashew Alm Classic 6/200g', 'Cashew Buttery Sprd 8/227g', 'Chives&Garlic 6/98g']
output = ['Cashew Alm Classic', 'Cashew Butter Sprd', 'Chives&Garlic']

data = pd.DataFrame(list(zip(product_name, output)), columns=['product_name', 'output'])

data

enter image description here

>Solution :


df['output2']=df['product_name'].str.extract(r'(.*?)\s(?=\d)')
df

#(.*?) : non-greedy capture everything
# \s: prior to space
# (?=\d) prior to a digit - positive lookahead
    product_name                output              output2
0   Cashew Alm Classic 6/200g   Cashew Alm Classic  Cashew Alm Classic
1   Cashew Buttery Sprd 8/227g  Cashew Butter Sprd  Cashew Buttery Sprd
2   Chives&Garlic 6/98g         Chives&Garlic       Chives&Garlic
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading