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?

1
  • 1
    Try '^[a-zA-Z][a-zA-Z, ]*$' or '^[a-zA-Z]+(?:[ ,]+[a-zA-Z]+)*$' Commented May 4, 2018 at 14:53

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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!!
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

1 Comment

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

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.