使用 VSCode,最新版本的 Python -V:3.1(64 位)
我正在尝试编写必须使用正则表达式进行编码的代码,并且它基本上必须检查代码格式是否正确。
例如,我必须创建一个匹配像
"3+4"
这样的表达式的模式。
(我不会在以下任何代码中包含
import re
,但请记住它是在原始代码中实现的)
考虑到这一点,我创建了以下模式:
var = r"^[a-zA-Z][a-zA-Z0-9]*$"
int1 = r"^[1-9][0-9]*$"
bool1 = r"^(True|False)$"
string = r"^#[a-zA-Z0-9]+#$"
sum1 = r'^\s*\+\s*$'
sub = r'^\s*\-\s*$'
prod = r'^\s*\*\s*$'
dif = r'^\s*\<\s*$'
div = r'^\s*\/\s*$'
eq= r'^\s*==\s*$'
我需要创建一个至少与
"3+4"
这样的字符串匹配的模式。在我做到这一点之后,我可以继续匹配其他类型的字符串,比如"#hello# = 10 / x"
,但是现在,让这篇文章专注于提到的第一个字符串。
为此,我创建了以下模式:
perm = r"^(" + int1 + r"|" + bool1+ r"|" + string + r"|" + var+ ")$"
oper = r"^(" + sum1+ r"|" + sub+ r"|" + prod + r"|" + dif + r"|" + div + r"|" + eq+ ")$"
我的主要想法是创建一个模式,允许
oper
和 perm
之间的连接,以及 oper
再次。
我对这件事有基本的了解,所以在尝试了很多不同的选择之后,我已经没有想法了。
我试过以下的
oper_bin = r"{0}{1}{2}".format(perm, oper, perm)
oper_bin = r"^(" + perm + ")" + r"(" + oper + ")" + r"(" + perm + ")$"
oper_bin = perm + oper + perm
但似乎都不起作用。
我以提到的第一个字符串为例,我得到的所有字符串都相同:
代码:
str = "3+4"
print(re.match(perm, str[0]))
print(re.match(oper, str[1]))
print(re.match(perm, str[2]))
print(re.match(oper_bin, str))
print(re.findall(oper_bin, str))
输出:
<re.Match object; span=(0, 1), match='3'>
<re.Match object; span=(0, 1), match='+'>
<re.Match object; span=(0, 1), match='4'>
None
[]
"3 + 4"
也应该匹配,但是 "3++4"
不应该。
欢迎任何帮助。
我将从单一类型和(二元)运算符开始,然后从那里慢慢构建。对于
int
和二进制 +
我们会得到类似的东西:
import re
int = r"[1-9][0-9]*" # not exactly correct, `0` and `00000` are an int in python and many others not included here.
# also notice your current int requires two digits!
# maybe 0|[1-9]\d* would be better (taken from JSON spec)
plus = r'\+'
# to start, maybe we can match the pattern: int space* plus space* int
regex = re.compile(fr'^{int}\s*{plus}\s*{int}$')
for pattern in ["3+4", "3++4", "3 + 4"]:
print (pattern, regex.match(pattern))
# 3+4 <re.Match object; span=(0, 3), match='3+4'>
# 3++4 None
# 3 + 4 <re.Match object; span=(0, 5), match='3 + 4'>