1

My code looks like this.

for userinput in sys.argv[1:]:
    pattern = re.compile(userinput, flags = re.IGNORECASE)
    if re.search(pattern, string):
        do action

I want to search through a string of text using this pattern but exclude the cases where the pattern exists in between a different word, such as 'hi' inside 'which'. So I tried putting the word boundary

pattern = re.compile('\buserinput\b', flags = re.IGNORECASE)

but I realized this will search the literal string 'userinput'. How do I add word boundaries to the patterns that change over the loop?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
sttsspjy
  • 31
  • 3
  • 1
    `'\b'` is a backspace, not a word boundary. `r'\b'` is a word boundary. You want to use a variable in a regex, so use `rf'\b{userinput}\b'` or alternatives. – Wiktor Stribiżew Apr 10 '21 at 12:52
  • @WiktorStribiżew thanks!! that works. Didn't know f string can be used in the regex functions – sttsspjy Apr 10 '21 at 12:58
  • Well, a regex is a piece of text, a string of characters. Surely f-strings can be used in regex functions. A more important thing though is to select the right boundary. – Wiktor Stribiżew Apr 10 '21 at 13:00

0 Answers0