【发布时间】:2016-03-28 18:43:23
【问题描述】:
在 python 中验证字符串以使其仅包含特定(预定义)单词或其他一些字符的最佳方法是什么 [e.g. +, -, /, *, (, ) ]?
我的最终目标是验证输入(将用作数学公式的字符串),例如:
foo = Valid
fooo = Invalid
bar = Valid
foo/(bar+foo) = Valid
foo*bar - foo = Valid
foo + tree = Invalid
+ = Invalid
我一直在寻找并找到类似的问题,但没有一个似乎完全符合我的需求。 我设法创建了一个有缺陷的解决方法,我执行以下操作:
allowed_words = ('foo', 'bar', ' + ') # and so on... which is tedious
input_str = raw_input("foo + bar")
split_string = re.split('(\W+)', input_str)
for word in split_string:
match = False
for allowed_word in allowed_words:
if word == allowed_word:
match = True
else:
pass
if match == True:
print "%s is valid" % word
else:
print "%s is NOT valid" % word
我也尝试过使用
if not re.match = ("(\b(?=foo\b|bar\b|\d+\b)\w+\b)|\s|[*/+()-]", input_str)
这似乎在这里工作:http://regexr.com(但我怀疑 re.match 不是正确的方法......)
有人可以告诉我实现目标的最佳方法吗?谢谢。
【问题讨论】:
-
这听起来很像您想要一种非常简单的特定领域语言而不是纯正则表达式解决方案 - 您需要有一些上下文概念才能做到这一点,这是正则表达式无法提供的你。有很好的Python parsing and lexing 解决方案。你想要一个词法分析器。
标签: python regex validation