0

Am I doing something wrong, or is the following behavior expected when searching a compiled regex in Python with the IGNORECASE flag? The strange behavior is that it appears I must define IGNORECASE when compiling a regex, but I cannot use the IGNORECASE flag when searching a compiled regex.

import re

regex_string = "test"

assert re.search(regex_string, "test")
assert re.search(regex_string, "TEST", re.IGNORECASE)

regex = re.compile(regex_string, re.IGNORECASE)
assert regex.search("test")
assert regex.search("TEST")
#assert regex.search("TEST", re.IGNORECASE) # appears logical but fails

regex2 = re.compile(regex_string)
assert regex2.search("test")
#assert regex2.search("TEST", re.IGNORECASE) # appears logical but fails
Dan Tanner
  • 2,229
  • 2
  • 26
  • 39
  • 2
    Possible duplicate of [Python: why does regex compiled with re.IGNORECASE drop first chars?](https://stackoverflow.com/questions/52026997/python-why-does-regex-compiled-with-re-ignorecase-drop-first-chars) – Sayse May 09 '19 at 20:06
  • May be a duplicate of this as well https://stackoverflow.com/questions/500864/case-insensitive-regular-expression-without-re-compile – Chris Farr May 09 '19 at 20:10
  • note: you create the variable `regex2` but don't use it at all, you still call `regex.search()` – truth May 10 '19 at 02:08
  • @truth thanks - corrected. About the duplicate question - yeah I suppose the answers to both questions are the same. This question might be useful to highlight the misuse in a simple example. – Dan Tanner May 10 '19 at 03:47

1 Answers1

1

Check the documentation for the python re module:

  • re.search(pattern, string, flags=0) allows flags as an optional argument. 3.7 documentation link
  • Pattern.search(string[, pos[, endpos]]) does not. The compiled pattern must have been compiled with any settings you wanted to apply. 3.7 documentation link
Triggernometry
  • 573
  • 2
  • 9
  • Thanks - missed that in the docs. As an inexperienced Python user I mistakenly presumed the compiler would complain about the invalid argument. – Dan Tanner May 10 '19 at 03:37