【问题标题】:Python regex find strings that only contain space [duplicate]Python正则表达式查找仅包含空格的字符串[重复]
【发布时间】:2018-09-13 14:08:42
【问题描述】:

我想在 Python 中使用正则表达式来查找为空或仅包含空格的字符串。

"    "  - True
" "     - True
""      - True
"  1  " - False

如何通过正则表达式做到这一点?

【问题讨论】:

    标签: python regex


    【解决方案1】:

    您可以使用re.findall 并从字符串的开头(^)和字符串的结尾($)锚定搜索:

    import re
    strings = ['    ', ' ', '', '  1  ']
    results = [i for i in strings if re.findall('^\s*$', i)]
    

    输出:

    ['    ', ' ', '']
    

    【讨论】:

    • @WiktorStribiżew 请看我最近的编辑。
    • 是的,第 1,000,000 个骗子,我见过很多次了。
    猜你喜欢
    • 1970-01-01
    • 2020-08-30
    • 2012-02-19
    • 2017-05-03
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    相关资源
    最近更新 更多