I am new to regex so please explain how you got to the answer. Anyway I want to know the best way to match input function from a separate python file.
For example:
match.py
a = input("Enter a number") b = input() print(a+b)
Now I want to match ONLY the input statement and replace it with a random number. I will do this in a separate file main.py
. So my aim is to replace input function in the match.py
with a random numbers so I can check the output will come as expected. You can think of match.py
like a coding exercise where he writes the code in that file and main.py
will be the file where it evaluates if the users code is right. And to do that I need to replace the input myself and check if it works for all kinds of inputs. I looked for “regex patterns for python input function” but the search did not work right. I have a current way of doing it but I don’t think it works in all kinds of cases. I need a perfect pattern which works in all kinds of cases referring to the python syntax. Here is the current main.py
I have (It doesn’t work for all cases I mean when you write a string with single quote, it does not replace but here is the problem I can just add single quote in pattern but I also need to detect if both are used):
# Evaluating python file checking if input 2 numbers and print sum is correct import re import subprocess input_pattern = re.compile(r"inputs?(["]?[w]*["]?)") file = open("match.py", 'r') read = file.read() file.close() code = read matches = input_pattern.findall(code) for match in matches: code = code.replace(match, '8') file = open("match.py", 'w') file.write(code) file.close() process = subprocess.Popen('python3 match.py', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out = process.communicate()[0] print(out == b"16n") file = open("match.py", 'w') file.write(read) file.close()
Please let me know if you don’t understand this question.
Advertisement
Answer
The following regex statement is very close to what you need:
inputs?((?(?=["'])["'].*["'])|))
I am using a conditional regex statement. However, I think it may need a nested conditional to avoid the situation that the user enters something like:
input(' text ")
But hopefully this gets you on the right track.