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
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With