1

I basically want to match strings like: "something", "some,thing", "some,one,thing", but I want to not match expressions like: ',thing', '_thing,' , 'some_thing'.

The pattern I want to match is: A string beginning with only letters and the rest of the body can be a comma, space or letters.

Here's what I did:

import re
x=re.compile('^[a-zA-z][a-zA-z, ]*') #there's space in the 2nd expression here
stri='some_thing'
x.match(str)

It gives me:

<_sre.SRE_Match object; span=(0, 4), match='some'>

The thing is, my regex somehow works but, it actually extracts the parts of the string that do match, but I want to compare the entire string with the regular expression pattern and return False if it does not match the pattern. How do I do this?

juztcode
  • 1,196
  • 2
  • 21
  • 46

2 Answers2

3

You use [a-Z] which matches more thank you think.

If you want to match [a-zA-Z] for both you might use the case insensitive flag:

import re
x=re.compile('^[a-z][a-z, ]*$', re.IGNORECASE)
stri='some,thing'

if x.match(stri):
    print ("Match")
else:
    print ("No match")

Test

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • I can't believe that wasted my 2 precious hours, I tested so much of patterns, and all was at fault was a simple case error. Thanks mate, that saved my life!! – juztcode May 04 '18 at 15:49
2

the easiest way would be to just compare the result to the original string.

import re
x=re.compile('^[a-zA-z][a-zA-z, ]*')
str='some_thing'
x.match(str).group(0) == str #-> False

str = 'some thing'
x.match(str).group(0) == str #-> True
brandonmack
  • 168
  • 2
  • 8
  • 1
    the problem is that, the string will be compared from user input, and that can be arbitrary length. So can't compare with fix strings – juztcode May 04 '18 at 15:34