简体   繁体   中英

Python regex not matching against pattern

I'm trying to write a block that will take a file path from the user and check that the file path is a) actually a legitimate file path that opens a file, and b) that the first and last line of the .txt file fit this pattern:

-53.750 120.900 49.805

As it is now, the code that I'm using is not pattern-matching and is accepting any file. Does anyone know which part of the code needs adjustment in order to get the desired filter? I feel like I'm missing something obvious.

This is what I'm trying:

while True:
    try:
        fileInput = input("What is the file path?: ")
        openedInput = open(fileInput, 'r')
        inputList = []
        for line in openedInput:
            inputList.append(line)
        firstLine = inputList[0]
        lastLine = inputList[-1]
        print(firstLine)
        print(lastLine)

        if not re.match('.[0-9]+.[0-9]+\s.[0-9]+.[0-9]+\s[0-9]+.[0-9]+',firstLine) and re.match('.[0-9]+.[0-9]+\s.[0-9]+.[0-9]+\s[0-9]+.[0-9]+',lastLine):
            print("The data file must be in XYZ format, please submit a usable file: ")
            continue
        break
    except:
        print("That file path was not valid, try again")

You have a problem of negation. What your code is currently doing is printing the error message only if the first line does not match and the last line does match.

It works fine with if not (re.match(regex,firstLine) and re.match(regex,lastLine)): , or if not re.match(regex,firstLine) or not re.match(regex,lastLine):

You need to add \\ before . in you regular expression. like this : [0-9]+ \\. [0-9]

Hope it helps, cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM