2012-12-28 49 views
1

我正在開發一個個人項目,該項目旨在打開用戶指定的文件,然後接受用戶輸入並將該輸入用作正則表達式來搜索文件。這樣做的目的是更深入地瞭解正則表達式如何工作,以及如何將它們合併到程序中。將用戶輸入用作正則表達式

我的問題在於,用戶給我的所有輸入都格式化爲一個字符串。所以(糾正我,如果我錯了),輸入[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。這將如何影響我的情況?它將肆虐與用戶包括「在輸入

回答

2

r"..."語法是唯一有用的,以防止蟒編譯器解釋的轉義序列(\n被轉換以換行符爲例)一旦編譯器解析,它將只是一個常規字符串

我們用`raw_input'讀取用戶的輸入,編譯器不執行任何轉義序列解釋。做任何事情,字符串都是alr正確解釋。

您可以像測試這個自己:

>>> x = r"[a-z]+\n" 
>>> y = raw_input("") 
[a-z]+\n 
>>> x == y 
True 
+0

非常好!非常感謝你。 – argonXM

0

從Python http://docs.python.org/2/library/re.html直接來自:

import re 
m = re.search(regexp_as_string, payload) 
m.group(0) #first occurence of the pattern 
+1

記得格式化用戶輸入(以消除討厭的結束行字符)。 – Ketouem

+0

或者你可以eval()用戶的輸入,但我不會推薦它(即使你正在處理高級用戶) – Ketouem

相關問題