我正试图在python中绕过regex模块。我试图从用户输入的一行文本中获得与以下模式相匹配的程序:
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")(预先谢谢:)
发布于 2021-07-20 21:13:11
您的表达式格式不太好,因为您使用了方括号,其中必须使用圆括号。[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发布于 2021-07-20 21:24:55
你使用的正则表达式在"/“的两边都需要1's,使用”regex“符号来暗示或语句,这样就可以选择"a”或"b",“a-b”。这将给您一个与"/“之前的”8-9 x 10-3“更符合的正则表达式。因此,当使用"( regex )”对想要单独表达的部分进行分组时,您可以使用一个与“(8-9 10-3)/(0-9 10-3)/(0-9 10-5)”更一致的正则表达式。
希望这能帮上忙!
https://stackoverflow.com/questions/68447713
复制相似问题