将点分隔的字符串拆分为单词但具有特殊情况

Dil*_*aev 4 python regex parsing split

不确定是否有一种简单的方法来拆分以下字符串:

'school.department.classes[cost=15.00].name'
Run Code Online (Sandbox Code Playgroud)

进入:

['school', 'department', 'classes[cost=15.00]', 'name']
Run Code Online (Sandbox Code Playgroud)

注意:我想保持'classes[cost=15.00]'完整.

jam*_*lak 6

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

更具体的版本:

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

详细:

>>> 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']
Run Code Online (Sandbox Code Playgroud)