Python 正则表达式匹配所有单词序列
我需要一个python正则表达式来匹配字符串中的所有(非空)单词序列,假设单词是非空白字符的任意非空序列 类似这样的东西:Python 正则表达式匹配所有单词序列,python,regex,Python,Regex,我需要一个python正则表达式来匹配字符串中的所有(非空)单词序列,假设单词是非空白字符的任意非空序列 类似这样的东西: s = "ab cd efg" re.findall(..., s) # ['ab', 'cd', 'efg', 'ab cd', 'cd efg', 'ab cd efg'] 最接近这一点的是使用regex模块,但仍然不是我想要的: regex.findall(r"\b\S.+\b", s, overlapped=True) # ['ab cd efg', 'cd ef
s = "ab cd efg"
re.findall(..., s)
# ['ab', 'cd', 'efg', 'ab cd', 'cd efg', 'ab cd efg']
最接近这一点的是使用regex
模块,但仍然不是我想要的:
regex.findall(r"\b\S.+\b", s, overlapped=True)
# ['ab cd efg', 'cd efg', 'efg']
另外,我想说清楚,我不想在那里有“ab efg”。类似于:
matches = "ab cd efg".split()
matches2 = [" ".join(matches[i:j])
for i in range(len(matches))
for j in range(i + 1, len(matches) + 1)]
print(matches2)
产出:
['ab', 'ab cd', 'ab cd efg', 'cd', 'cd efg', 'efg']
您可以做的是匹配所有字符串及其空格,然后将相邻的片段连接在一起。(这与Maxim的方法类似,虽然我独立开发了此方法,但保留了空白)
导入正则表达式
s=“ab cd efg”
subs=regex.findall(r“\S+\S*”,S)
def组合(l):
out=[]
对于范围内的i(len(subs)):
对于范围内的j(i+1,len(subs)+1):
out.append(“.join(subs[i:j]).strip())
返回
打印(组合(子组合))
首先查找与单词匹配的所有\S+\S*
,后跟任意数量的空格,然后获取所有连续切片,将其合并,并从其右侧删除空格
如果空白总是一个空格,那么就使用Maxim的方法;它更简单、更快,但不保留空格。没有正则表达式:
import itertools
def n_wise(iterable, n=2):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
iterables = itertools.tee(iterable, n)
for k, it in enumerate(iterables):
for _ in range(k):
next(it, None)
return zip(*iterables)
def foo(s):
s = s.split()
for n in range(1, len(s)+1):
for thing in n_wise(s, n=n):
yield ' '.join(thing)
s = "ab cd efg hj"
result = [thing for thing in foo(s)]
print(result)
>>>
['ab', 'cd', 'efg', 'hj', 'ab cd', 'cd efg', 'efg hj', 'ab cd efg', 'cd efg hj', 'ab cd efg hj']
>>>
因为正则表达式是贪婪的,所以不能匹配
'ab cd'
,因为任何重复的正则表达式都会一直匹配到底为什么s.split()
不能满足您的需要?