一、整個正則表達式帶括號,檢測到幾次,就會輸出幾組。輸出檢測到的字符串外,還要帶有之后的字符串。
import re string="abcdefg acbdgef abcdgfe cadbgfe" regex=re.compile("((\w+)\s+\w+)") print(regex.findall(string)) #輸出:[('abcdefg acbdgef', 'abcdefg'), ('abcdgfe cadbgfe', 'abcdgfe')]
二、正則表達式中帶有括號的,檢測到幾次,就輸出幾次,只輸出括號內檢測到的部分。
import re string="abcdefg acbdgef abcdgfe cadbgfe" regex1=re.compile("(\w+)\s+\w+") print(regex1.findall(string)) #輸出:['abcdefg', 'abcdgfe']
三、正則表達式不帶括號,檢測到幾次,就輸出幾次,只輸出檢測到的部分。
import re string="abcdefg acbdgef abcdgfe cadbgfe" regex2=re.compile("\w+\s+\w+") print(regex2.findall(string)) #輸出:['abcdefg acbdgef', 'abcdgfe cadbgfe']