每天一点python:正则表达式中的findall方法
举例:使用findall获取所有匹配的正则表达式文本,然后逐一替换。
1 #! python3 2 """ 3 A regular expression example: find all matched text using findall() 4 """ 5 import re 6 7 text = "The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events. " 8 9 # Match ADJECTIVE,NOUN or VERB. Independent object relative to the text to be matched 10 wordRegex = re.compile(r'(ADJECTIVE|NOUN|VERB)') 11 # Pass the target text into a method of the regex object 12 # findall(): return a list of all matched texts 13 matches = wordRegex.findall(text) 14 for match in matches: 15 # Get input from command line 16 newWord = str(input("Enter a {}:".format(match.lower()))) 17 # Replace matched text with newWord, repalce only once, for the first one. 18 text = text.replace(match, newWord, 1) 19 20 print(text)