gpt4 book ai didi

Python - 如何将此模式(数字/数字)与正则表达式匹配?

转载 作者:行者123 更新时间:2023-12-04 07:21:53 27 4
gpt4 key购买 nike

我试图了解python中的正则表达式模块。我试图让我的程序从用户输入的一行文本中匹配以下模式:
8-13 之间的数字“/” 0-15 之间的数字
例如:8/2、11/13、10/9 等。
我想出的模式是:upstream = re.compile(r'[8-9|1[0-3][/][0-9|1[0-5]')然而,这个正则表达式的工作结果好坏参半:

Enter a slot/port : 8/2    
['8/2'] # This is correct

Enter a slot/port : 1/0
['1/0'] # This should print the "else" statement

Enter a slot/port : 8/15
['8/1'] # The output is incomplete
问题似乎源于正斜杠,但我不确定。我知道我需要一些帮助来解决这个问题。如果有人能帮我解决这个问题,我将不胜感激。
完整的脚本如下。
import re
pattern = re.compile(r'[8-9|1[0-3][/][0-9|1[0-5]')

upstream = input("Enter a slot/port : ")

if re.search((pattern), upstream):
print(re.findall(pattern, upstream))
else:
print("We have a problem")
提前致谢 :)

最佳答案

您的表达式格式不正确,因为您在必须使用圆括号的地方使用了方括号。 [8-9|1[0-3][0-9|1[0-5]两者都是错误的模式,如 [8-9[0-9不是封闭的字符类。
采用

\b(?:[89]|1[0-3])/(?:[0-9]|1[0-5])\b
regex proof .
解释
--------------------------------------------------------------------------------
\b the boundary between a word char (\w) and
something that is not a word char
--------------------------------------------------------------------------------
(?: group, but do not capture:
--------------------------------------------------------------------------------
[89] any character of: '8', '9'
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
1 '1'
--------------------------------------------------------------------------------
[0-3] any character of: '0' to '3'
--------------------------------------------------------------------------------
) end of grouping
--------------------------------------------------------------------------------
/ '/'
--------------------------------------------------------------------------------
(?: group, but do not capture:
--------------------------------------------------------------------------------
[0-9] any character of: '0' to '9'
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
1 '1'
--------------------------------------------------------------------------------
[0-5] any character of: '0' to '5'
--------------------------------------------------------------------------------
) end of grouping
--------------------------------------------------------------------------------
\b the boundary between a word char (\w) and
something that is not a word char

关于Python - 如何将此模式(数字/数字)与正则表达式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68447713/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com