为什么正则表达式'r [1900-2023] +'不返回1900到2023之间的值范围?

Bas*_*nda -5 python regex

我在Python中有以下代码:

txt = 'Ted\'s date of birth is 5-6-2005 and he started college at 08-5-2019'

year = re.compile(r'[1900-2023]+')

res = year.findall(txt)

for i in res:
    print(i)
Run Code Online (Sandbox Code Playgroud)

上面的代码返回:

200
0
2019
Run Code Online (Sandbox Code Playgroud)

由于[1900-2023]返回的是1900to 范围之间的任何匹配项2023,为什么在这里它返回200和0(超出此范围)?而且,它甚至没有返回处于此范围内的2005。

dvo*_*dvo 5

在其他的答案/评论指出,[1900-2023]不匹配之间的任何数字19002023,而匹配是任何字符190-2,或3。对于您的特定情况,您可以自己制作一个与这些数字匹配的模式:

19[0-9]{2}|20[01][0-9]|202[0-3]
Run Code Online (Sandbox Code Playgroud)

说明:

19[0-9]{2}  - "19" and exactly 2 numbers that range 0 - 9 (1900 - 1999)
|           - OR
20[01][0-9] - "20" and either a 0 or 1 and another number that ranges 0 - 9 (2000 - 2019)
|           - OR
202[0-3]    - "202" and one number in a range 0 - 3 (2020 - 2023)
Run Code Online (Sandbox Code Playgroud)