正则表达式匹配,如果不匹配则更改格式

时间:2019-10-17 23:49:07

标签: python regex

我需要帮助以REGEX格式匹配文件的每一行,如果不匹配,则基于REGEX格式重新格式化该行。

关于文件:每行唯一的变化是每行qr后的10位数字(1234567890)。

问题:现在我无法进行比赛。我的输出只是以正确的格式打印ELSE输出。

谢谢您的帮助!

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..

1 个答案:

答案 0 :(得分:1)

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

  • 动态数字的前缀使用“ dn”而不是“ qr”
  • 在动态数字前匹配一个附加的'1'
  • 量词'{'被转义,因此与文字匹配
  • 最后一个值的前缀使用'sp'而不是'mo'

以下是解决这些问题的正则表达式示例:

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

也在regular expressions 101中看到该正则表达式。

相关问题