A regular expression to extract a given number of words around a matching word

I was looking for a way to capture the words around the match, but they were too complicated for my business. All I need is a regular expression to capture, say 10 words before and after the matching word. Can anyone help me create a template for this?

For example, suppose a sentence (does not make sense):

    sentence = "The hairy yellow, stinkin' dog, sat round' the c4mpfir3 and ate the brown/yellow smore that the kids(*adults) were makin."

and suppose we want to match 3 words before and after smore (already cleared to match). Output signal:

   "ate the brown/yellow smore that the were"

now allows you to take an example of what you need to take one word before and after stinkin ':

   "yellow, stinkin' dog"

Another example. "Village":

   "yellow, stinkin' dog, round' the and

Now make a new sentence:

   sentence = "If the problem is still there after 30 minutes. Give up"

If I tried to combine this word and took 2 words before and after the exit:

   "is still there after minutes"

, 10, , ? , , . , , , . , .

    ('[a-zA-Z\'.,/]{3}(word_to_match)[a-zA-Z\'.,/]{3}')

-2
2

((?:\w*\s*){2})\s*word3\s*((?:\s*\w*){2})

1 , 2 ,

2 , .

, , .

, http://worksol.be/regex.html

enter image description here

-1

"word": . : , . Python .

\w - "" ( ), \w - . :

m = re.search(r'((\w+\W+){0,4}grab(\W+\w+){0,4})', sentence)
print m.groups()[0]

, \S ( , ) \S ( ):

re.search(r'((\S+\s+){0,4}grab(\s+\S+){0,4})', sentence)

, . , , . ( "", , ).

-1

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


All Articles