简体   繁体   中英

How to extract strings using regex pattern in python?

I am trying to extract the file names, which are the text after the time and before.filetype, by using regex - "str.extract" in python.

You could try:

                                         # 5 fields /fname/ext
df['filename'] = df['text'].str.extract(r'(?:\w+ ){5}(.*)\.[^.]*$')

output:

   index                                                           text                        filename
0      1        sample 1 root root 349802 Nov 1 2000 introduction.json*         Nov 1 2000 introduction
1      2           sample 1 root root 1234 Oct 1 10:26 test_housing.csv        Oct 1 10:26 test_housing
2      3  sample 1 root root 5983025 Nov 1 10:32 test_train_housing.csv  Nov 1 10:32 test_train_housing
3      4                  sample 1 root root 1252 Oct 1 10:32 _test.csv               Oct 1 10:32 _test
4      5            sample 1 root root 938 Oct 1 10:32 _train_small.csv        Oct 1 10:32 _train_small
5      6               sample 1 root root 9909303 Oct 5 2000 README.md*               Oct 5 2000 README
df['filename'] = df['text'].str.extract('(\w+)[.].*$')

result:

['introduction', 'test_housing', 'test_train_housing', '_test', '_train_small', 'README']

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