-2

This code returns None, what am I doing wrong? I'm assuming it has something to do with special characters

test=re.search('The Girl Who Played with Fire (Millennium #2)', 'The Girl Who Played with Fire (Millennium #2)',re.IGNORECASE)
print(test)

2 Answers2

-1

The parenthesis are being treated as grouping operators when the string is used as a pattern.

Try this instead:

test=re.search(
    'The Girl Who Played with Fire [(]Millennium #2[)]',
    'The Girl Who Played with Fire (Millennium #2)',
    re.IGNORECASE
)
Michael Speer
  • 3,738
  • 2
  • 16
  • 10
  • This works! How do I add the forward slashes before the parentheses using re.sub? – Adib Menchali Jul 06 '20 at 03:31
  • if you're just looking for whether a string is a substring of another, it will be far easier just to use `in` than to escape strings into regexes for the purpose – Michael Speer Jul 06 '20 at 03:37
  • No, I have a list of book titles and I want my code to return True when the user enters a title that is present in my list. My code works with all book titles except for those having parentheses in them, so I'm thinking to re.sub the user's input to escape ( and ) but I've never used re.sub before and I'm not sure how to do that. – Adib Menchali Jul 06 '20 at 03:47
  • Nevermind, I can just use replace() to do it lol – Adib Menchali Jul 06 '20 at 03:57
-1

You have to escape ( and ) in Regex:

test=re.search(
   'The Girl Who Played with Fire \(Millennium #2\)', # <- NOTICE
   'The Girl Who Played with Fire (Millennium #2)',
   re.IGNORECASE)
print(test)
Farshid Ashouri
  • 11,423
  • 5
  • 40
  • 56