详解Python中正则匹配TAB及空格的⼩技巧
在正则中,使⽤.*可以匹配所有字符,其中.代表除\n外的任意字符,*代表0-⽆穷个,⽐如说要分别匹配某个⽬录下的⼦⽬录:
>>> import re
>>> match = re.match(r"/(.*)/(.*)/(.*)/", "/usr/local/bin/")
>>> ups()
('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!")
>>> up(1)
'\t\t Python '
>>>
要想匹配到TAB和空格的混合字符,可以使⽤下⾯的两个⼩技巧:
1). 使⽤\s来匹配
正则匹配或>>> import re
>>> match = re.match(r"Hello(\s*)(.*)World!", "Hello Python World!"
)
>>> ups()
('\t\t ', 'Python ')
>>>
2). 使⽤[\t ]来匹配
>>> import re
>>> match = re.match(r"Hello([\t ]*)(.*)World!", "Hello Python World!"
)
>>> ups()
('\t\t ', 'Python ')
>>>
上⾯的⼩技巧,都能完美匹配TAB和空格键.
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论