簡體   English   中英

正則表達式匹配所有單詞序列

[英]Regex to match all sequences of words

我需要一個python正則表達式,它將匹配字符串中所有(非空)單詞序列,假設word是非空白字符的任意非空序列。

有點像這樣的東西:

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' ,我不想在那里'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的方法,雖然我確實獨立開發了這個,但這保留了空白)

import regex
s = "ab cd efg"
subs = regex.findall(r"\S+\s*", s)
def combos(l):
	out = []
	for i in range(len(subs)):
		for j in range(i + 1, len(subs) + 1):
			out.append("".join(subs[i:j]).strip())
	return out
print(combos(subs))

在線嘗試!

這首先找到所有\\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']
>>>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM