[英]Python - How do I match this pattern (number/number) with regex?
我正在尝试了解 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
请参阅正则表达式证明。
解释
--------------------------------------------------------------------------------
\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
您正在使用的正则表达式要求“/”两边都为 1,请使用“|” 符号暗示 OR 语句,这样就可以选择“a 或”b”,“a|b”。这会给你一个更符合“[8-9]|1[0-3]”的正则表达式在“/”之前和“[0-9]|1[0-5]”之后。所以总的来说,当使用“(regex)”来分组你想要单独表达的部分时,你可能会得到一个正则表达式更符合“([8-9]|1[0-3])/([0-9]|1[0-5])”。
希望这是有帮助的!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.