我正在創建一種編程語言。對於這種語言,我創建了一個將其編譯爲Python的程序。我不需要詞法分析器,因爲大多數語法都可以用正則表達式轉換爲Python。Python中的多個正則表達式
這是我到目前爲止有:
import re
infile = input()
output = open(infile + ".py","w")
input = open(infile + ".hlx")
# I'm aware the .hlx extension is already taken, but it doesn't really matter.
for line in input:
output.write(re.sub(r'function (\S+) (\S+) =', r'def \1(\2):', line))
for line in input:
output.write(re.sub(r'print(.+)', r'print(\1)', line))
for line in input:
output.write(re.sub(r'call (\S+) (\S+)', r'\1(\2)', line))
# More regexes go here, eventually.
input.close()
output.close()
我不得不把每個正則表達式在一個單獨的語句,因爲如果我把它們放在一起,它會替換每行3次。
這裏的問題是它只執行其中一個正則表達式,這是第一個正則表達式。順序在這裏並不重要,但我仍然需要該程序來執行所有的正則表達式。我將如何做到這一點?
順便說一句,這是我想在我的語言來代替代碼:
function hello input =
print "Hello, ", input, "!"
hello "world"
這裏就是我想用Python來取代它的代碼:
def hello(input):
print("Hello, " + input + "!")
hello("world")
)'的開頭的文件。另外,爲什麼不將每個're.sub'調用的輸出分配給一個變量,以便在必須寫入之前,可以在同一行上調用每個're.sub'。 – bunji