【发布时间】:2018-02-08 16:58:22
【问题描述】:
期望的结果:
我想要一个解析器函数,它接受一串“指令”。
此字符串将使用string.split(";") 切碎并去除空格。我想检查每个“印章”是否与一堆(10+)正则表达式匹配。每个表达式还具有捕获组定义的值,我稍后将使用这些值“执行命令”。
问题:
我目前有一个长而复杂的 if、elseif、else 语句,这是非常不可取的,因为它使我的代码更难管理,也更难被其他人阅读。
目前的想法:
基本上,我想使用字典来模拟 switch 语句。但是我对正则表达式的经验很少,我能够做出正确的“表达式”来捕捉我想要的“指令”。但是我对pythons正则表达式包的工作原理非常陌生。
朝着正确方向迈出的一步已经是一个函数,在给定一个字符串和一个列表或正则表达式的字典的情况下,该函数将返回匹配的正则表达式。
示例代码:(请原谅缩进:))
class PreparedConstraintsCollection(ConstraintsCollectionABC):
not_pattern = re.compile("^not([-+]*[0-9]+)$")
ex_pattern = re.compile("^ex([-+]*[0-9]+)$")
more_pattern = re.compile("^>([-+]*[0-9]+)$")
less_pattern = re.compile("^<([-+]*[0-9]+)$")
interval_pattern = re.compile("^([-+]*[0-9]+)<x<([-+]*[0-9]+)$")
def parse_constraints_string(self, restriction_string: str) -> set:
"""
The overly-complex function to parse the restriction control sequence strings
Control Sequence Meaning Explanation
---------------------------------------------------------------------------------------------
+ Positive only Allow only positive values
- Negative only Allow only negative values
notX Not X value Do not allow values X
exX Must be X Only allow values X
>X More then X Values must be more then X
<X Less then X Values must be less then X
M<x<N Interval M, N Must be more then M but less then N
:param restriction_string: a string with control sequences
:return: return the gathered restriction instances, conserve only unique
"""
gathered_constraints = set()
for control_seq in restriction_string.split(";"):
stripped = control_seq.strip().replace(" ", "")
if stripped == "":
continue
elif stripped == "+":
gathered_constraints.add(res_gallery.PositiveConstraint())
elif stripped == "-":
gathered_constraints.add(res_gallery.NegativeConstraint())
elif self.not_pattern.match(stripped):
searched = re.search(self.not_pattern, stripped)
param = float(searched.group(1))
gathered_constraints.add(res_gallery.NotExactValueConstraint(param))
elif self.ex_pattern.match(stripped):
searched = re.search(self.ex_pattern, stripped)
param = float(searched.group(1))
gathered_constraints.add(res_gallery.ExactValueConstraint(param))
elif self.more_pattern.match(stripped):
searched = re.search(self.more_pattern, stripped)
param = float(searched.group(1))
gathered_constraints.add(res_gallery.GreaterThanConstraint(param))
elif self.less_pattern.match(stripped):
searched = re.search(self.less_pattern, stripped)
param = float(searched.group(1))
gathered_constraints.add(res_gallery.LessThanConstraint(param))
elif self.interval_pattern.match(stripped):
searched = re.search(self.interval_pattern, stripped)
param1, param2 = float(searched.group(1)), float(searched.group(2))
gathered_constraints.add(res_gallery.IntervalConstraint(param1, param2))
else:
raise ValueError("Restriction string could not be parsed!")
return gathered_constraints
【问题讨论】:
-
如果您发布一些示例代码及其预期输出,可能会更容易为您提供帮助。感谢您对问题的详细描述!很少有新用户像您一样在他们的问题上投入如此多的精力。简洁明了:)
-
贴代码,谢谢!
标签: python regex python-3.x switch-statement