Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正则表达式匹配并更改格式(如果不匹配';不匹配_Python_Regex - Fatal编程技术网

Python 正则表达式匹配并更改格式(如果不匹配';不匹配

Python 正则表达式匹配并更改格式(如果不匹配';不匹配,python,regex,Python,Regex,我需要帮助将文件的每一行与REGEX格式匹配,如果不匹配,则根据REGEX格式重新格式化该行 关于文件:每行中唯一更改的是每行qr后面的10位数字(1234567890) 问题:现在我不能参加比赛。我的输出只是打印其他输出,即使格式正确 提前感谢您的帮助 import re filepath = 'fruit.txt' def main(): # mode function to check that the file is in open mode. with open(f

我需要帮助将文件的每一行与REGEX格式匹配,如果不匹配,则根据REGEX格式重新格式化该行

关于文件:每行中唯一更改的是每行qr后面的10位数字(1234567890)

问题:现在我不能参加比赛。我的输出只是打印其他输出,即使格式正确

提前感谢您的帮助

import re

filepath = 'fruit.txt'

def main():
    # mode function to check that the file is in open mode.
    with open(filepath) as fp:
        cnt = 1
        for line in fp:
            #Matching correct format: fruit_id (iid 43210, qr 1234567890,mo 001212121)
            matchLn = re.match(r'fruit_id\s+\(iid\s+43210,\s+qr\s+1\d\{10},mo\s+001212121\)', line, re.M|re.I)
            print("Matching Pattern with : {}".format(line))
            #if pattern.match(line):
            if matchLn:
                print('Matched format:', cnt)
            else:
                print('Check the format of the line:', cnt)
                # I need to make sure the line matches the format)
            cnt = cnt + 1
main()
fruit.txt:

   fruit_id (iid 43210, qr 1234567890,mo 001212121)
   fruit_id (iid 43210, qr 1235567890,mo 001212121)
   fruit_id (iid 43210, qr 1225367890,mo 001212121)
   fruit_id (iid 43210, qr 1274567890,mo 001212121)
   fruit_id (iid 43210, qr 1279567890,mo 001212121)
   fruit_id (iid 43210, qr 1245637890,mo 001212121)
   fruit_id (iid 43210, qr 1234457890,mo 001212121)
   fruit_id (iid 43210, qr 1234532890,mo 001212121)
输出:

Matched format: 1
Matched format: 2
Matched format: 3
Matched format: 4
Matched format: 5
Matched format: 6
Matched format: 7
Matched format: 8
Copying the file to a path..

您的正则表达式包含以下问题:

  • 动态编号的前缀使用“dn”而不是“qr”
  • 在动态编号之前再匹配一个“1”
  • 量词“{”被转义,因此匹配为文字
  • 最后一个值的前缀使用“sp”而不是“mo”
下面是修复这些问题的示例正则表达式:

\s*fruit_id\s+\(iid\s+43210,\s+qr\s+\d{10},mo\s+001212121\)

另请参见中的正则表达式。

显示输入、所需和实际输出的示例(编辑问题)。如果您可以通过编写一个简单函数来解决问题,那么为什么要使用正则表达式?您的问题是什么?请澄清。同时,请进行说明。有关更多提示,请参见。抱歉,伙计们,我仍然是一个noob。重新格式化了问题。