简体   繁体   中英

Regular Expression For Comma Separated Word Python

How to get all the words which are comma separated before a particular word in python using regular expression.

example:

s=" A,B particular_word is the C,D particular_word"

output for particular_word AB C D

You can use the following regex to find the stuff you're looking for:

import re
s = " A,B particular_word is the C,D particular_word"
word_finder = r'(?:([^\W]+),([^\W]+))\Wparticular_word'
matches = re.findall(word_finder, s)

This will return a list of tuples with the words inside them. Note that this work by NOT matching word's ( \W ).

You can also flatten the list as follows:

words = [w for word_tuple in matches for w in word_tuple]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM