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

2024-05-23 13:45:28 发布

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

我需要帮助匹配文件的每一行与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()

你知道吗水果.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..

Tags: 文件thetoreidformat格式line
1条回答
网友
1楼 · 发布于 2024-05-23 13:45:28

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

  • 动态编号的前缀使用“dn”而不是“qr”
  • 另一个“1”在动态编号之前匹配
  • 量词{被转义,因此匹配为literal
  • 最后一个值的前缀使用“sp”而不是“mo”

下面是一个正则表达式修复这些问题的示例:

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

另请参见regular expressions 101中的正则表达式。你知道吗

相关问题 更多 >