仅 Python 正则表达式匹配空间 [英] Python regex match space only

查看:55
本文介绍了仅 Python 正则表达式匹配空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python3中,如何精确匹配空白字符而不是换行符\n或制表符\t?

In python3, how do I match exactly whitespace character and not newline \n or tab \t?

我看到了来自 Regex match space not \n 答案,但对于以下示例它不起作用:

I've seen the \s+[^\n] answer from Regex match space not \n answer, but for the following example it does not work:

a='rasd\nsa sd'
print(re.search(r'\s+[^ \n]',a))

结果是 <_sre.SRE_Match 对象;span=(4, 6), match='\ns'>,这是匹配的换行符.

Result is <_sre.SRE_Match object; span=(4, 6), match='\ns'>, which is the newline matched.

推荐答案

不需要特殊组.只需创建一个带有空格字符的正则表达式.空格字符没有任何特殊含义,仅表示匹配一个空格".

No need for special groups. Just create a regex with a space character. The space character does not have any special meaning, it just means "match a space".

RE = re.compile(' +')

所以对于你的情况

a='rasd\nsa sd'
print(re.search(' +', a))

愿意

<_sre.SRE_Match object; span=(7, 8), match=' '>

这篇关于仅 Python 正则表达式匹配空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆