0

How come the code below is not matching the space character?

import re

hasSpace = re.compile(' ')

string = 'hello world'

if(hasSpace.match(string)):
    print("Found a space")
else:
    print("No space")

I also tried using:

hasSpace = re.compile('\s')

but it's not matching either. I also tried to add an r to make the string raw, but same result.

Any clue why?

5
  • 1
    see the match function doc, match tries to match from the start. Since there isn't a space char at the start, it fails. Commented Mar 23, 2015 at 16:02
  • Why would you use Regex for this? if ' ' in string: is all you need. Commented Mar 23, 2015 at 16:02
  • @iCodez the pattern is more complex, but I need to be able to match the space first. Commented Mar 23, 2015 at 16:04
  • 1
    Replace match by search Commented Mar 23, 2015 at 16:04
  • @AvinashRaj you are correct. The problem is the match function. Thanks Commented Mar 23, 2015 at 16:06

3 Answers 3

1

Replace match by search:

>>> if(hasSpace.search(string)):
...      print("Found a space")
... else:
...     print("No space")
...
Found a space
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Will pick your answer once time allows.
1

You probably want to use the search method. search "scans through a string, looking for any location where this RE matches."

import re

hasSpace = re.compile(' ')

string = 'hello world'

if(hasSpace.search(string)):
    print("Found a space") # gets printed
else:
    print("No space")

string = 'helloworld'

if(hasSpace.search(string)):
    print("Found a space")
else:
    print("No space") # gets printed

What you were trying to use is match, which "determines if the RE matches at the beginning of the string."

Comments

0

If you really want to get to the answer using match then you can do it this way (not recommended.) since match starts from the beginning you will need to match the 5 letters of the word 'hello' with '.....' and then match the space

import re
hasSpace = re.compile('..... ')
string = 'hello world'
if(hasSpace.match(string)):
  print("Found a space")
else:
  print("No space")

output

Found a space

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.