re.match(r"hello","hello")
re.match(正则表达式,需要处理的字符串)
ipython3: In [12]: re.match(r"hello","hello world") Out[12]: <_sre.SRE_Match object; span=(0, 5), match='hello'> In [14]: re.match(r"[hH]ello","Hello world") Out[14]: <_sre.SRE_Match object; span=(0, 5), match='Hello'> In [15]: re.match(r"[hH]ello","hello world") Out[15]: <_sre.SRE_Match object; span=(0, 5), match='hello'> In [17]: re.match(r"速度与激情\d","速度与激情1") Out[17]: <_sre.SRE_Match object; span=(0, 6), match='速度与激情1'> In [18]: re.match(r"速度与激情\d","速度与激情2") Out[18]: <_sre.SRE_Match object; span=(0, 6), match='速度与激情2') \d 表示匹配一位数字 0-9 In [19]: ret = re.match(r"速度与激情[12345678]","速度与激情2") In [20]: ret.group() Out[20]: '速度与激情2' [] 表示里面所列的 In [22]: re.match(r"速度与激情[1-8]","速度与激情2").group() Out[22]: '速度与激情2' In [23]: re.match(r"速度与激情[1-8]","速度与激情9").group() --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-23-9c4f3f67ebee> in <module>() ----> 1 re.match(r"速度与激情[1-8]","速度与激情9").group() AttributeError: 'NoneType' object has no attribute 'group' In [25]: re.match(r"速度与激情[123678]","速度与激情3").group() Out[25]: '速度与激情3' In [26]: re.match(r"速度与激情[1-36-8]","速度与激情3").group() Out[26]: '速度与激情3'
In [28]: re.match(r"速度与激情[1-8abcd]","速度与激情a").group() Out[28]: '速度与激情a' In [29]: re.match(r"速度与激情[1-8abcd]","速度与激情e").group() --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-29-27b5df124b44> in <module>() ----> 1 re.match(r"速度与激情[1-8abcd]","速度与激情e").group() AttributeError: 'NoneType' object has no attribute 'group' In [30]: re.match(r"速度与激情[1-8abcdA-Z]","速度与激情F").group() Out[30]: '速度与激情F' In [31]: re.match(r"速度与激情\w","速度与激情F").group() Out[31]: '速度与激情F' In [32]: re.match(r"速度与激情\w","速度与激情f").group() Out[32]: '速度与激情f' In [33]: re.match(r"速度与激情\w","速度与激情3").group() Out[33]: '速度与激情3' In [34]: re.match(r"速度与激情\w","速度与激情哈").group() Out[34]: '速度与激情哈' \w 匹配单词字符,即a-z,A-Z,0-9,下划线,中文
In [37]: re.match(r"速度与激情\s\d","速度与激情 3").group() Out[37]: '速度与激情 3' In [38]: re.match(r"速度与激情\s\d","速度与激情\t1").group() Out[38]: '速度与激情\t1' In [39]: re.match(r"速度与激情\s\d","速度与激情\n1").group() Out[39]: '速度与激情\n1' \s 匹配空白,即空格,tab键,\n
\大写,正好与小写相反。