0

I have very basic knowledge of Python 3.x but what I needed to do was to look through a text file and ensure a file is not being written using restricted characters.

So far I have this:

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!")

I am not able to remove all the whitespace from the text file and that is what I think is causing this the file to go into error. Is there a way I can remove all whitespace from the data string or have re.search accept whitespace.

Thank you for your help.

1 Answers1

0

I found the solution: using \s matches whitespace character.

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!")
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92