#python 3.6#蔡军生
#http://blog.csdn.net/caimouse/article/details/51749579
#
import re
text = 'This is some text -- with punctuation.'
print(text)
print()
patterns = [
(r'^(\w+)', 'word at start of string'),
(r'(\w+)\S*$', 'word at end, with optional punctuation'),
(r'(\bt\w+)\W+(\w+)', 'word starting with t, another word'),
(r'(\w+t)\b', 'word ending with t'),
]
for pattern, desc in patterns:
regex = re.compile(pattern)
match = regex.search(text)
print("'{}' ({})\n".format(pattern, desc))
print(' ', match.groups())
print()
结果输出如下:
This is some text -- with punctuation.
'^(\w+)' (word at start of string)
('This',)
'(\w+)\S*$' (word at end, with optional punctuation)
('punctuation',)
'(\bt\w+)\W+(\w+)' (word starting with t, another word)
('text', 'with')
'(\w+t)\b' (word ending with t)
('text',)