【问题标题】:Restricting use of special characters using python使用python限制使用特殊字符
【发布时间】:2020-05-30 17:50:11
【问题描述】:

我对 Python 3.x 有非常基本的了解,但我需要做的是查看一个文本文件并确保文件不是使用受限字符编写的。

到目前为止,我有这个:

import re

#Open and simplify file - turn to string
with open('test.cfg', 'r') as file:
    data = file.read().replace('\n'' ', '').replace(' ','')

#Compare text to allowed characters
if re.search('^[A-Za-z0-9' '\,\%\[\]\=_-]*$', data):
    print("All good")
else:
    print ("Error!")

我无法从文本文件中删除所有空格,这就是我认为导致该文件出错的原因。有没有办法可以从数据字符串中删除所有空格或让 re.search 接受空格。

感谢您的帮助。

【问题讨论】:

  • This 听起来很有希望

标签: regex python-3.x removing-whitespace


【解决方案1】:

我找到了解决方案:使用 \s 匹配空白字符。

import re

#Open and simplify file - turn to string
with open('test.cfg', 'r') as file:
    data = file.read().replace('\n'' ', '').replace(' ','')
if not re.search('^[A-Za-z0-9' '\s\,\.\&\%\[\]\=_-]*$', data):
    print ("Error!")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-14
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    相关资源
    最近更新 更多