Search code examples
pythonregexwlst

Why does my re.search command is not working?


I have this 'if' condition inside my script:

if ( re.search(argVariable, newArgs) ):

However it fails when I passed on a certain value for 'argVariable'

Sample output:

Searching for the argument: -XX:+HeapDumpOnOutOfMemoryError
argVariable: "-XX:+HeapDumpOnOutOfMemoryError"
"-XX:+HeapDumpOnOutOfMemoryError" is MISSING, Adding...

I'm sure that my 'newArgs' variable already has it. (See below)

New args: -Xverbosetimestamp -Xverbose:memory -XX:+CrashOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError

What am I doing wrong?


Solution

  • I figured that I need to re.escape the actual value right before I use it. Then I need to use the compiled version to avoid special characters inside the variable to be interpreted like a regex' special character:

    compiledArgVariable = re.compile(re.escape(argVariable))
    if ( re.search(compiledArgVariable, newArgs) ):
    

    Sample output shows that it finds the exact value:

    argVariable: "-XX:+HeapDumpOnOutOfMemoryError"
    "-XX:+HeapDumpOnOutOfMemoryError" found to be an EXISTING argument. Checking if it has the correct value...
    "-XX:+HeapDumpOnOutOfMemoryError" HAS the correct value. Skipping..