当前位置:主页 > 软件编程 > Python代码 >

详解Python中正则匹配TAB及空格的小技巧

时间:2021-05-13 08:15:11 | 栏目:Python代码 | 点击:

在正则中,使用.*可以匹配所有字符,其中.代表除\n外的任意字符,*代表0-无穷个,比如说要分别匹配某个目录下的子目录:

>>> import re
>>> match = re.match(r"/(.*)/(.*)/(.*)/", "/usr/local/bin/")
>>> match.groups()
('usr', 'local', 'bin')
>>>

比如像上面,使用(.*)就能很好的匹配,但如果字符串中里面即有TAB键,又有空格,要匹配出来,如何匹配呢?比如说像"Hello          Python World!", Hello到Python之间,即有空格键,又有TAB键,而且可能有1到多个,这个直接用(.*)就连"Python "给匹配到了,从下面可以看到两个TAB,两个空格键,还有Python都匹配到了。

>>> import re
>>> match = re.match(r"Hello(.*)World!", "Hello      Python World!")
>>> match.group(1)
'\t\t Python '
>>>

要想匹配到TAB和空格的混合字符,可以使用下面的两个小技巧:

1). 使用\s来匹配

>>> import re
>>> match = re.match(r"Hello(\s*)(.*)World!", "Hello       Python World!"
)
>>> match.groups()
('\t\t ', 'Python ')
>>>

2). 使用[\t ]来匹配

>>> import re
>>> match = re.match(r"Hello([\t ]*)(.*)World!", "Hello      Python World!"
)
>>> match.groups()
('\t\t ', 'Python ')
>>>

上面的小技巧,都能完美匹配TAB和空格键.

您可能感兴趣的文章:

相关文章