被括號括起來的表達式將作為一個整體,也就是一個分組:
In [43]: str = "Jan 26 16:41:27 localhost dhclient[1480]: bound to 192.168.119.128 -- renewal in 750 seconds." In [44]: reg = re.compile(r'(\w+ \d+ [\d:]+) (\w+) .*') # 把日期和時間匹配到一組,把來源主機匹配到一組 In [45]: reg.findall(str) # 另外,雖然.*匹配到剩下的所有內容,但默認只打印匹配到的分組的內容 Out[45]: [('Jan 26 16:41:27', 'localhost')]
我們可以給分組起一個名字,這種分組叫做有名分組:
In [52]: str = "Jan 26 16:41:27 localhost dhclient[1480]: bound to 192.168.119.128 -- renewal in 750 seconds." In [53]: reg = re.compile(r'(?P<datetime>\w+ \d+ [\d:]+) (?P<hostname>\w+) .*') # 有名分組的語法:(?P<group_name>pattern) In [54]: result = reg.search(str) # 需要用search()方法來進行匹配,因為該方法有group()可以指定打印哪個匹配到的分組 In [55]: result.group('datetime') # 根據組名來獲取匹配到的分組的內容 Out[55]: 'Jan 26 16:41:27' In [56]: result.group('hostname') Out[56]: 'localhost' In [57]: result.groupdict() # 還可以用groupdict()以字典的形式返回所有分組 Out[57]: {'datetime': 'Jan 26 16:41:27', 'hostname': 'localhost'}