Regex to match all word sequences

I need a python regular expression that will match all (non-empty) sequences of words in a string, assuming the word is an arbitrary non-empty sequence of non-white characters.

Something that will work as follows:

s = "ab cd efg"
re.findall(..., s)
# ['ab', 'cd', 'efg', 'ab cd', 'cd efg', 'ab cd efg']

The closest I got to this was using the module regex, but still not what I want:

regex.findall(r"\b\S.+\b", s, overlapped=True)
# ['ab cd efg', 'cd efg', 'efg']

Also, to be clear, I do not want to have 'ab efg'there.

+4
source share
3 answers

Sort of:

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)

Outputs:

['ab', 'ab cd', 'ab cd efg', 'cd', 'cd efg', 'efg']
+4
source

, , . ( , , )

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; , .

0

Without regex:

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']
>>>
0
source

Source: https://habr.com/ru/post/1686434/


All Articles