How to write regular expression that covers small and capital letters of a specific word?

Question:

I am trying to use regular expression to find a specific word (with small or capital letters) in a text.

Examples are:

  • none
  • None
  • NONE

However, the following code doesn’t find the pattern in sample texts.

import re

txt_list = ["None" , "none", "[none]", "(NONE", "Hi"]
pattern = "/bnoneb/i"


for txt in txt_list:
    if re.search(pattern, txt):
        print(f'Found {txt}')

What is the cause of the above issue? Is the "pattern" incorrect?

Asked By: Mohammad

||

Answers:

Do not use slashes to delimit the regular expression. The syntax in Python is different. You can use (?i) to ignore case. (Additionally, escape the backslashes or use raw strings.)

pattern = "(?i)\bnone\b"

You can also pass the re.IGNORECASE flag to re.search.

pattern = r"bnoneb"
for txt in txt_list:
    if re.search(pattern, txt, re.IGNORECASE):
        print(f'Found {txt}')
Answered By: Unmitigated
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.