//search lines that start with the string “From:”
import re hand = open(‘mbox-short.txt‘) for line in hand: line = line.rstrip() if re.search(‘ˆFrom:‘, line) : print line
// match any of the strings “From:”, “Fxxm:”, “F12m:”, or “[email protected]:”
1 import re 2 hand = open(‘mbox-short.txt‘) 3 for line in hand: 4 line = line.rstrip() 5 if re.search(‘ˆF..m:‘, line) : 6 print line
//search lines that start with “From:”, followed by one or more characters (“.+”), followed by an at-sign
1 import re 2 hand = open(‘mbox-short.txt‘) 3 for line in hand: 4 line = line.rstrip() 5 if re.search(‘ˆFrom:[email protected]‘, line) : 6 print line
//uses findall() to find the lines with email addresses in them,
1 import re 2 s = ‘Hello from [email protected] to [email protected] about the meeting @2PM‘ 3 lst = re.findall(‘\[email protected]\S+‘, s) 4 print lst
The output of the program would be:[‘[email protected]‘, ‘[email protected]‘]
The “\S+” matches as many non-whitespace characters as possible.
时间: 2024-10-13 00:43:07