簡體   English   中英

Python 正則表達式未按預期返回

[英]Python Regular expression not returning as expected

我無法理解這個正則表達式的輸出。 我正在使用以下正則表達式在文本中查找日期:

^(?:(1[0-2]|0?[1-9])-(3[01]|[12][0-9]|0?[1-9])|(3[01]|[12][0-9]|0?[1-9])-(1[0-2]|0?[1-9]))-(?:[0-9]{2})?[0-9]{2}$

它似乎正確匹配文本中的模式,但我對返回值感到困惑。

對於這個測試字符串:

TestString = "10-20-2015"

它返回這個:

[('10', '20', '', '')]

如果我把 () 放在整個正則表達式中,我會得到這個返回:

[('10-20-2015', '10', '20', '', '')]

我希望它簡單地返回完整的日期字符串,但它似乎打破了結果,我不明白為什么。 將我的正則表達式包裝在 () 中會返回完整的日期字符串,但也會返回 4 個額外的值。

我如何使它只匹配完整的日期字符串而不是字符串的小部分?

從我的控制台:

Python 3.4.2 (default, Oct  8 2014, 10:45:20) 
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> pattern = "^(?:(1[0-2]|0?[1-9])-(3[01]|[12][0-9]|0?[1-9])|(3[01]|[12][0-9]|0?[1-9])-(1[0-2]|0?[1-9]))-(?:[0-9]{2})?[0-9]{2}$"
>>> TestString = "10-20-2015"
>>> re.findall(pattern, TestString, re.I)
[('10', '20', '', '')]
>>> pattern = "(^(?:(1[0-2]|0?[1-9])-(3[01]|[12][0-9]|0?[1-9])|(3[01]|[12][0-9]|0?[1-9])-(1[0-2]|0?[1-9]))-(?:[0-9]{2})?[0-9]{2}$)"
>>> re.findall(pattern, TestString, re.I)
[('10-20-2015', '10', '20', '', '')]
>>> 
>>> TestString = "10--2015"
>>> re.findall(pattern, TestString, re.I)
[]
>>> pattern = "^(?:(1[0-2]|0?[1-9])-(3[01]|[12][0-9]|0?[1-9])|(3[01]|[12][0-9]|0?[1-9])-(1[0-2]|0?[1-9]))-(?:[0-9]{2})?[0-9]{2}$"
>>> re.findall(pattern, TestString, re.I)
[]

根據回復,這是我的答案:((?:(?:1[0-2]|0[1-9])-(?:3[01]|[12][0-9]|) 0[1-9])|(?:3[01]|[12][0-9]|0[1-9])-(?:1[0-2]|0[1-9]) )-(?:[0-9]{2})?[0-9]{2})

每個()是一個捕獲組, (1[0-2]|0?[1-9])捕獲10(3[01]|[12][0-9]|0?[1-9])捕獲20 ,依此類推。 當您將所有內容包圍在() ,它位於另一個()之前,並且匹配了所有內容。 您可以忽略捕獲的組(稱為non-captured group ,使用(?:)代替()

我們可以使用最重要的 re 函數之一 - search() 來做到這一點。 此函數掃描字符串,查找此 RE 匹配的任何位置。

import re

text = "10-20-2015"

date_regex = '(\d{1,2})-(\d{1,2})-(\d{4})'

""" 
\d in above pattern stands for numerical characters [0-9].
The numbers in curly brackets {} indicates the count of numbers permitted.
Parentheses/round brackets are used for capturing groups so that we can treat 
multiple characters as a single unit.

"""

search_date = re.search(date_regex, text)

# for entire match
print(search_date.group())
# also print(search_date.group(0)) can be used
 
# for the first parenthesized subgroup
print(search_date.group(1))
 
# for the second parenthesized subgroup
print(search_date.group(2))
 
# for the third parenthesized subgroup
print(search_date.group(3))
 
# for a tuple of all matched subgroups
print(search_date.group(1, 2, 3))

上面提到的每個打印語句的輸出:

10-20-2015
10
20
2015
('10', '20', '2015')

希望這個答案能消除你的疑慮:-)

暫無
暫無

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

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