Regex - Python: Capture three (3) words after a specific word -
hello have following code:
str1 = "hello, meet @ train station of berlin after 6 o' clock" match = re.compile(r' @ \w+ \w+ \w+') match.findall(str1) is there better way "\w+ \w+ \w" example capture specific number of words?
yes. specify particular count match, use curly-braces. e.g.,:
match = re.compile(r'at ((\w+ ){3})') which gives:
>>> print match.findall(str1) [('the train station ', 'station ')] in general, capture n words after word, regex be:
'word\s+((?:\w+(?:\s+|$)){n})' where ?: designates "non-capturing" group, \s designates whitespace, | means "or", , $ means "end of string". therefore:
>>> print re.compile(r'at\s+((?:\w+(?:\s+|$)){3})').findall(str1) ['the train station ']
Comments
Post a Comment