0

I am trying to match a string 'hello world' to a sentence. I think that means it searches the sentence for that string and returns a value that indicates a success.

But when I try this code, all that prints out is 'None'.

import re
sentence = "why do we write hello world so often?"
match1 = re.match('hello world', sentence)
print match1
Maroun
  • 94,125
  • 30
  • 188
  • 241
Eric
  • 11
  • 1
  • 1
  • 7

1 Answers1

2

match looks only at the beginning of the string.

You should use search instead:

match1 = re.search('hello world', sentence)

Note that you shouldn't use regex for this specific task. hello world is a very specific text, you can use in to check if it's contained in a string. Regexes should be used when you have a pattern.

If you insist to use match, you should change your regex to:

match1 = re.match('.*hello world', sentence)

Now .* matches everything until the hello world token, and the regex "hello world" will match the string "hello world" in your sentence.

Maroun
  • 94,125
  • 30
  • 188
  • 241