I am trying to match multiple elements to a single string with little to no luck.
The regex should return all the elements that are in the token array, as many times as they occur in the string in the same order they occur, this would be a basic lexing algorithm for a very basic C compiler.
Is there a way i could transform my array to a working pattern where the elements are essentially unordered? I have not found any other patterns that could work in my case as the elements of my array could appear anywhere in the string.
file = """
int main() {
return 2;
}"""
tokens = ['{', '}', '\(', '\)', ';', "int", "return", '[a-zA-Z]\w*', '[0-9]+']
def lex(file):
results = []
for i in tokens:
r = re.match(r".?"+i+".",file)
if r != None:
results.append(r.group())
return r
the output should be something like this:
r = ["int", "main", "(", ")", "{", "return", "2", ";", "}"]