我正在開發一個個人項目,該項目旨在打開用戶指定的文件,然後接受用戶輸入並將該輸入用作正則表達式來搜索文件。這樣做的目的是更深入地瞭解正則表達式如何工作,以及如何將它們合併到程序中。將用戶輸入用作正則表達式
我的問題在於,用戶給我的所有輸入都格式化爲一個字符串。所以(糾正我,如果我錯了),輸入[a-z] +將導致搜索表達式「[a-z] +」。這是一個問題,如果我想r「[a-z] +」作爲我的搜索表達式,因爲把它作爲用戶輸入將會給我「r」[a-z] +「」(如果我錯了,再糾正一下)。這顯然不適用於正則表達式。如何格式化輸入以使r「[a-z] +」的輸入保持r「[a-z] +」?
這是有問題的代碼部分。在功能參數的文本文件,從程序的另一部分進口,並在正則表達式搜索使用:
def new_search_regex(textFile):
"""Query for input, then performs RegEx() with user's input"""
global totalSearches
global allSearchResults
# ask user for regular expression to be searched
expression = raw_input("Please enter the Regular Expression to be searched: ")
# perform initial regex search
foundRegex = re.search(expression, textFile)
# if Regex search successful
if foundRegex != None:
# Do complete regex search
foundRegex = re.findall(expression, textFile)
# Print result
print "Result: " + str(foundRegex)
# Increment global total
totalSearches += 1
# create object for result, store in global array
reg_object = Reg_Search(totalSearches, expression, foundRegex)
allSearchResults.append(reg_object)
print "You're search number for this search is " + str(totalSearches) # Inform user of storage location
# if Regex search unsuccessful
else:
print "Search did not have any results."
return
注:最後我創建結果的對象,並將其存儲在一個全局數組。
這也假設現在用戶能夠勝任進入非系統銷燬正則表達式。我很快就會開始添加錯誤檢查,例如在用戶輸入中使用.escape。這將如何影響我的情況?它將肆虐與用戶包括「在輸入
非常好!非常感謝你。 – argonXM