简体   繁体   中英

Extract substring from a string using Python regex

I am working with data frames. One of my column look like this

                   X
4028    Toolx-2022-01-18_15-26-09.blf.26
4029    Temperaturelow-2022-01-18_15-26-09.blf.27
4031    Temperaturehigh2022-01-18_15-26-09.blf.28
4032    low2022-01-18_15-26-09.blf.29
4032    high2022-01-18_15-26-09.blf.30
Name: X, dtype: object

I want my output like this

                  X
4028    2022-01-18 15-26-09 26
4029    2022-01-18 15-26-09 27
4030    2022-01-18 15-26-09 28
4031    2022-01-18 15-26-09 29
4032    2022-01-18 15-26-09 30
Name: X, dtype: object 

Can anyone please help me how to do this in Python?

We can use str.extract here:

df["X"] = df["X"].str.extract(r'(\d{4}-\d{1,2}-\d{1,2})_(\d{2}-\d{2}-\d{2}).*\.(\d+)', r'\1 \2 \3')

Here is a regex demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM