Python 正则表达式编译拆分字符串,以便单词首先出现



假设我得到了一个这样的字符串

text = "1234 I just ? shut * the door"

我想使用带有 re.compile(( 的正则表达式,这样当我拆分列表时,所有单词都在前面。

即它应该看起来像这样。

text = ["I", "just", "shut", "the", "door", "1234", "?", "*"]

如何使用 re.compile(( 以这种方式拆分字符串?

import re
r = re.compile('regex to split string so that words are first').split(text)

如果您需要更多信息,请告诉我。

谢谢你的帮助。

IIUC,你不需要re。只需将str.splitsorted一起使用:

sorted(text.split(), key=lambda x: not x.isalpha())

输出:

['I', 'just', 'shut', 'the', 'door', '1234', '?', '*']

您可以将sortedre.findall一起使用:

import re
text = "1234 I just ? shut * the door"
r = sorted(text.split(), key=lambda x:(x.isalpha(), x.isdigit(), bool(re.findall('^W+$', x))), reverse=True)

输出:

['I', 'just', 'shut', 'the', 'door', '1234', '?', '*']

你不能用一个正则表达式来做到这一点。您可以编写一个正则表达式来获取所有单词,然后编写另一个正则表达式来获取其他所有内容。

import re
text = "1234 I just ? shut * the door"
r = re.compile(r'[a-zA-Z]+')
words = r.findall(text)
r = re.compile(r'[^a-zA-Zs]+')
other = r.findall(text)
print(words + other) # ['I', 'just', 'shut', 'the', 'door', '1234', '?', '*']

最新更新