使用python限制使用特殊字符

问题描述 投票:0回答:1

我具有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接受空格。

谢谢您的帮助。

regex python-3.x removing-whitespace
1个回答
0
投票

我找到了解决方案:使用\ 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!")


© www.soinside.com 2019 - 2024. All rights reserved.