Python Regex到findall分隔的子字符串

2024-05-29 03:38:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串:

test2 = "-beginning realization 5 -singlespace -multispaceafter  not-this-one -whitespace\t\n -end"

我想找到所有以减号(-)开头的子字符串。你知道吗

我能找到所有的“除了”最后一个事件:

re.findall(ur"\B-(.*?)\s", test2)

返回[u'beginning', u'singlespace', u'multispaceafter', u'whitespace']

我可以找到“最后的事件”:

re.findall(ur"\B-(.*?)\Z", test2)

返回[u'end']

但是,我想要一个返回的正则表达式

[u'beginning', u'singlespace', u'multispaceafter', u'whitespace', u'end']


Tags: 字符串re事件notthisoneendwhitespace
3条回答

您可以使用非捕获组来声明后跟空格或字符串结尾。你知道吗

>>> re.findall(r'\B-(.*?)(?:\s|$)', test2)

尽管如此,我建议使用以下方法代替\B和非捕获组:

>>> re.findall(r'(?<!\S)-(\S+)', test2)

你也可以试试下面的代码

>>> test2 = "-beginning realization 5 -singlespace -multispaceafter  not-this-one -whitespace\t\n -end"
>>> m = re.findall(r'(?:\s|^)-(\S+)', test2)
>>> m
['beginning', 'singlespace', 'multispaceafter', 'whitespace', 'end']
(?<=\s)-(.*?)(?=\s|$)|(?<=^)-(.*?)(?=\s|$)

试试看这个。看到了吗演示。你知道吗

http://regex101.com/r/cN7qZ7/6

相关问题 更多 >

    热门问题