【问题标题】:Split string based on regexp without consuming characters [duplicate]基于正则表达式拆分字符串而不消耗字符[重复]
【发布时间】:2014-08-20 02:11:43
【问题描述】:

我想像下面这样拆分一个字符串

text="one,two;three.four:"

进入列表

textOut=["one", ",two", ";three", ".four", ":"]

我试过了

import re
textOut = re.split(r'(?=[.:,;])', text)

但这不会分裂任何东西。

【问题讨论】:

  • 只是一个公式注释,它不是“消耗字符”,更像是保留分隔符

标签: python regex string split


【解决方案1】:

我会在这里使用re.findall 而不是re.split

>>> from re import findall
>>> text = "one,two;three.four:"
>>> findall("(?:^|\W)\w*", text)
['one', ',two', ';three', '.four', ':']
>>>

下面是上面使用的正则表达式模式的细分:

(?:      # The start of a non-capturing group
^|\W     # The start of the string or a non-word character (symbol)
)        # The end of the non-capturing group
\w*      # Zero or more word characters (characters that are not symbols)

如需了解更多信息,请参阅here

【讨论】:

    【解决方案2】:

    我不知道你的字符串中还会出现什么,但这能解决问题吗?

    >>> s='one,two;three.four:'
    >>> [x for x in re.findall(r'[.,;:]?\w*', s) if x]
    ['one', ',two', ';three', '.four', ':']
    

    【讨论】:

    • 谢谢,这解决了我的问题。虽然我对命令本身的理解有点迷失了。
    猜你喜欢
    • 2010-10-16
    • 2021-03-06
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多