>>> re.findall(r"(\d{2})","a123 d56789")
['12', '56', '78']
>>> re.findall(r"a(\d{2})","a123 d56789")
['12']
>>> re.findall(r"a(\d{2})","a123 a56789")
['12', '56']
>>> re.findall(r"(a(\d{2}))","a123 a56789")
[('a12', '12'), ('a56', '56')]
1 统计文章的字母个数
>>> re.findall(r"[a-zA-Z]","ab 78 cd 69\n")
['a', 'b', 'c', 'd']
>>> len(re.findall(r"[a-zA-Z]","ab 78 cd 69\n"))
4
2 统计文章数字个数
>>> len(re.findall(r"\d","ab 78 cd 69\n"))
4
3 统计文章中的单词个数
>>> len(re.findall(r"\b[a-zA-Z]+\b","ab 78 cd 69\n"))
2
5 获取某个网页的所有链接
>>> re.findall(r'href="(.*?)"','<a href="http://fuwu.sogou.com/" target="_blank"
')
['http://fuwu.sogou.com/']
>>> re.findall(r'href="(.+?)"','<a href="http://fuwu.sogou.com/" target="_blank"
')
['http://fuwu.sogou.com/']
>>> re.search(r"href=\'(.*?)\' ","href='http://www.baidu.com' target=_").grou
p(1)
'http://www.baidu.com'
>>> re.findall(r"href=\'(.*?)\' ","href='http://www.baidu.com' target=_")
['http://www.baidu.com']
6 删除文章中所有数字
>>> re.sub(r"\d+","","ab 78 cd 69 3b 4e h890h")
'ab cd b e hh'
>>> p = re.compile(r"\d")
>>> result = p.split("ab 78 cd 69 3b 4e h890h")
>>> print(result)
['ab ', '', ' cd ', '', ' ', 'b ', 'e h', '', '', 'h']
>>> "".join(result)
'ab cd b e hh'
7 删除后统计一下删除了几组数
>>> re.subn(r"\d+","","ab 78 cd 69 3b 4e h890h")
('ab cd b e hh', 5)
>>> re.subn(r"\d+","","ab 78 cd 69 3b 4e h890h")[1]
5
8 匹配一个IP
>>> re.match(r"[2][0-4][0-9]\.|[2][5][0-5]\.|[1][0-9]{2}\.|[1-9][0-9]{0,1}\.|0\.
","255.")
<_sre.SRE_Match object; span=(0, 4), match='255.'>
>>> re.match(r"([2][0-4][0-9]\.|[2][5][0-5]\.|[1][0-9]{2}\.|[1-9][0-9]{0,1}\.|0\
.)([2][0-4][0-9]\.|[2][5][0-5]\.|[1][0-9]{2}\.|[1-9][0-9]{0,1}\.|0\.)([2][0-4][0
-9]\.|[2][5][0-5]\.|[1][0-9]{2}\.|[1-9][0-9]{0,1}\.|0\.)([2][0-4][0-9]|[2][5][0-
5]|[1][0-9]{2}|[1-9][0-9]{0,1}(?!\d)|0)","255.20.255.255")
<_sre.SRE_Match object; span=(0, 14), match='255.20.255.255'>
>>> re.match(r'(([01]{0,1}\d{0,1}\d|2[0-4]\d|25[0-5])\.){3}([2][0-4][0-9]|[2][5]
[0-5]|[1][0-9]{2}|[1-9][0-9]{0,1}(?!\d)|0)',"2.2.2.255")
<_sre.SRE_Match object; span=(0, 9), match='2.2.2.255'>
9 统计开头不是a的所有单词
>>> re.findall(r"\b[^a][a-zA-Z]+\b","abc cde fgi 2ad ")
[' cde', ' fgi', '2ad'] #错了
```python
>>> re.findall(r"\b[b-zB-Z]+\b","abc cde fgi 2ad ")
['cde', 'fgi']
>>> re.findall(r"\b(?!a)[b-zB-Z]+\b","abc cde fgi 2ad ")
['cde', 'fgi']
10 匹配1900年到2999年
```python
>>> re.match(r"19\d{2}年|2\d{3}年","1900年")
<_sre.SRE_Match object; span=(0, 5), match='1900年'>
>>> re.match(r"19\d{2}年|2\d{3}年","2999年")
<_sre.SRE_Match object; span=(0, 5), match='2999年'>
>>> re.match(r"19\d{2}年|2\d{3}年","1920年")
<_sre.SRE_Match object; span=(0, 5), match='1920年'>
>>> re.match(r"19\d{2}年|2\d{3}年","1820年")
>>> re.match(r"19\d{2}年|2\d{3}年","3000年")
>>> re.match(r"(19\d{2}|2\d{3})年","1920年")
<_sre.SRE_Match object; span=(0, 5), match='1920年'>
1204

被折叠的 条评论
为什么被折叠?



