Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

splitting a dot delimited string into words but with a special case

Not sure if there is an easy way to split the following string:

'school.department.classes[cost=15.00].name'

Into this:

['school', 'department', 'classes[cost=15.00]', 'name']

Note: I want to keep 'classes[cost=15.00]' intact.

like image 614
Dilshod Tadjibaev Avatar asked Jan 14 '23 06:01

Dilshod Tadjibaev


1 Answers

>>> import re
>>> text = 'school.department.classes[cost=15.00].name'
>>> re.split(r'\.(?!\d)', text)
['school', 'department', 'classes[cost=15.00]', 'name']

More specific version:

>>> re.findall(r'([^.\[]+(?:\[[^\]]+\])?)(?:\.|$)', text)
['school', 'department', 'classes[cost=15.00]', 'name']

Verbose:

>>> re.findall(r'''(                      # main group
                    [^  .  \[    ]+       # 1 or more of anything except . or [
                    (?:                   # (non-capture) opitional [x=y,...]
                       \[                 # start [
                       [^   \]   ]+       # 1 or more of any non ]
                       \]                 # end ]
                    )?                    # this group [x=y,...] is optional
                   )                      # end main group
                   (?:\.|$)               # find a dot or the end of string
                ''', text, flags=re.VERBOSE)
['school', 'department', 'classes[cost=15.00]', 'name']
like image 138
jamylak Avatar answered Jan 31 '23 11:01

jamylak