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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2021-04-03 我要评论

在正则中,使用.*可以匹配所有字符,其中.代表除\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和空格键.

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们