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

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -