与lin的正则表达式行匹配

2024-09-30 06:34:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用regex匹配文件中的行来编写一种有趣的小语言。到目前为止,我掌握的情况如下:

import re

code=open("code.txt", "r").read()

outputf=r'output (.*)'
inputf=r'(.*) = input (.*)'
intf=r'int (.*) = (\d)'
floatf=r'float (.*) = (\d\.\d)'
outputq=re.match(outputf, code)
if outputq:
    print "Executing OUTPUT query"
    exec "print %s" %outputq.group(1)

inputq=re.match(inputf, code)
if inputq:
    print "Executing INPUT query"
    exec "%s=raw_input(%s)"%(inputq.group(1), inputq.group(2))

intq=re.match(intf, code)
if intq:
    exec "%s = %s"%(intq.group(1), intq.group(2))
    exec "print %s"%(intq.group(1))
else:
    print "Invalid syntax"

代码在匹配中起作用,例如:

int x = 1

但它只会匹配第一行并停止匹配,而忽略我要匹配的其余代码。如何将文件中的每一行与regex定义匹配?你知道吗


Tags: 文件reinputifmatchgroupcoderegex
2条回答

您使用的是re.match(),这意味着您的正则表达式必须匹配整个字符串(在本例中是整个文件)。如果您迭代文件中的每一行,那么.match()将起作用。或者你可能想看看re.search()re.findall()和其他类似的替代品。你知道吗

看起来您的代码需要遍历文件中的行:How to iterate over the file in python

.read()读作一行,在.read()代码上使用.split("\n")或使用.readlines()。你知道吗

然后遍历这些行并测试您的命令。 目前,您将整个代码作为一行。你要逐行检查所有的行。你知道吗

编辑:

为此,创建一个函数

然后用readlines()读取行

最后使用函数对行进行迭代

就像这样:

import re

outputf=r'output (.*)'
inputf=r'(.*) = input (.*)'
intf=r'int (.*) = (\d)'
floatf=r'float (.*) = (\d\.\d)'

def check_line(line):
    outputq=re.match(outputf, line)
    if outputq:
        print ("Executing OUTPUT query")
        exec ("print (%s)" % outputq.group(1))

    inputq=re.match(inputf, line)
    if inputq:
        print ("Executing INPUT query")
        exec ("%s=raw_input(%s)"%(inputq.group(1), inputq.group(2)))

    intq=re.match(intf, line)
    if intq:
        exec ("%s = %s"%(intq.group(1), intq.group(2)))
        exec ("print (%s)"%(intq.group(1)))
    else:
        print ("Invalid syntax")


code=open("code.txt", "r").readlines()

for line in code:
    check_line(line)

这段代码仍然会返回一个错误,这与问题无关。因此,请考虑是否正确地分配了变量。你知道吗

相关问题 更多 >

    热门问题