1

I have to search for a pattern either inside the content of a variable or inside a data file. Below is the code I have so far:

import re

UserSpecifiedPattern = "segfault"

# find every instance of a user specified pattern
pattern =  re.compile( rb'(\.\W+)?([^.]?segfault[^.]*?\.)',
                       re.DOTALL | re.IGNORECASE | re.MULTILINE )

My problem is, how does one specify a variable to "re.compile". Meaning, I'm storing the actual pattern to be searched into a variable. And I'm then giving that variable to re.compile. The below is what I presume should work, but it isn't:

import re

UserSpecifiedPattern = "segfault"

# find every instance of a user specified pattern
pattern =  re.compile( rb'(\.\W+)?([^.]?UserSpecifiedPattern[^.]*?\.)',
                       re.DOTALL | re.IGNORECASE | re.MULTILINE )

I'm guessing this should be it?

import re

UserSpecifiedPattern = "segfault"

# find every instance of a user specified pattern
pattern =  re.compile( rb'(\.\W+)?([^.]?{UserSpecifiedPattern}[^.]*?\.)',
                       re.DOTALL | re.IGNORECASE | re.MULTILINE )
0

1 Answer 1

1

searching a regex with a bytes input works, but of course your variable name is treated literally.

You have to inject your variable, for instance by using format on the string, then encode to bytes (bytes object doesn't have format so encode it afterwards (you cannot use b prefix here):

pattern =  re.compile(r'(\.\W+)?([^.]?{}[^.]*?\.)'.format(UserSpecifiedPattern).encode(),
                   re.DOTALL | re.IGNORECASE | re.MULTILINE )

notes:

  • it works for this particular pattern which doesn't make use of {} to repeat expressions. If you have to use that, double the braces: ex: {{1,5}}
  • depending on the pattern you're passing, you may need to use re.escape on it if you want regex to see it literally (it doesn't matter much with words)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.