Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : Splitting a string by numbers, letters and -_

Let's say that I have a string like this one

string = 'rename_file_1122--23-_12'

Is there a way to split this like that

parts = ['rename','_','file','_','1122','--','23','-_','12']

I tried with the regular expression but it does not work

import re

name_parts = re.findall('\d+|\D+|\w+|\W+', string)

The result was:

['rename_file_', '1122', '--', '23', '-_', '12']

########## Second part

If I have a string like this one :

string2 = 'Hello_-Marco5__-'

What are the conditions that I need to use to get :['Hello','_-','Marco','5','__-']. My goal is to split a string y groups of letters,digits ans '-_'.

Thanks fors yours answers

like image 455
Maikiii Avatar asked Dec 17 '22 12:12

Maikiii


1 Answers

You can use

re.findall(r'[^\W_]+|[\W_]+', string)

See the regex demo.

Regex details:

  • [^\W_]+ - one or more chars other than non-word and _ chars (so, one or more letters or digits)
  • | - or
  • [\W_]+ - one or more non-word and/or _ chars.

See a Python demo:

import re
string = 'rename_file_1122--23-_12'
name_parts = re.findall(r'[^\W_]+|[\W_]+', string)
print(name_parts)
# => ['rename', '_', 'file', '_', '1122', '--', '23', '-_', '12']
like image 187
Wiktor Stribiżew Avatar answered Dec 27 '22 02:12

Wiktor Stribiżew