簡體   English   中英

為什么以下正則表達式在Python中不起作用?

[英]Why doesn't the following regular expression work in Python?

我有以下代碼:

regularexpression = r'([-\w]*\w)? ?: ?([-"\#\w\s_]*\w?);'
outputfr = re.findall(regularexpression, inputdata, re.IGNORECASE)
return data

應該捕獲以“;”結尾的單詞,連字符和其他字符。 所以:

(hello-nine: hello, six, seven; hello-five: six eight)將輸出為[('hello-nine','hello,六個,七個'),('hello-五個','六個八')

如果final-number: "seventy", "sixty", "fifty", forty sentiy final-number: "seventy", "sixty", "fifty", forty是用戶輸入(輸入數據)的一部分,則regularexpression不會捕獲它。 我希望它輸出為[('final-number', '"seventy", "sixty", "fifty", "forty")]

為什么是這樣?

在您的正則表達式中,第二組:

([-"\#\w\s_]*\w?)

需要進行更改,以使其與逗號匹配:

([-"\#\w\s_,]*\w?)

您的示例輸入->輸出不一致。 在第一種情況下,逗號分隔的項目保持在一起,但是在第二種情況下,它們是單獨的列表元素。 另外,您是否要刪除括號? 引號? 通過給予實際值澄清inputdata並顯示正是你想要返回(包括剝離引號,括號中)是什么。 永遠不會分配data變量。

使用.split(";")可能是一個更好的起點...

inputdata = "(hello-nine: hello, six, seven; hello-five: six eight)"
mylist = inputdata.split(";")
# here either use regexp or another split, depending on what you want...
subset = [x.split(":") for x in mylist]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM