Search code examples
pythonregexmatchpython-re

Find exact match with regular expression without preleading string in python


I have a text file called my_file.txt that has the following content:

                                  R.A.O.S-VARIATION WITH WAVE PERIOD/FREQUENCY
                              VEL R.A.O.S-VARIATION WITH WAVE PERIOD/FREQUENCY
                              ACC R.A.O.S-VARIATION WITH WAVE PERIOD/FREQUENCY
                              SOME OTHER STRING 

Now, I want to find the string R.A.O.S-VARIATION WITH WAVE PERIOD/FREQUENCY without any of the two other choises that have either VEL or ACC in it using a regular expression. There are white spaces before those strings.

How do I get the correct match using:

re.search(regex, line)

How should the regular expression look like that finds the desired string, without the two other options? I prefer to not specify all preleading white spaces in the string.


Solution

  • For a fixed-string match like this, you don't need a regular expression.

    Use this instead:

    if line.strip() == "R.A.O.S-VARIATION WITH WAVE PERIOD/FREQUENCY":
        # do stuff
    

    If you really want to use a regular expression, use re.fullmatch() to match the whole line:

    if re.fullmatch(r"\s*R\.A\.O\.S-VARIATION WITH WAVE PERIOD/FREQUENCY\s*", line):
        # do stuff