Home > database >  How to extract strings using regex pattern in python?
How to extract strings using regex pattern in python?

Time:02-21

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.

CodePudding user response:

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

CodePudding user response:

df['filename'] = df['text'].str.extract('(\w )[.].*$')

result:

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