1

I'm using following code to check the string matches the pattern using regex. For the ptr2 shouldn't matches the pattern but result has matches. What is wrong?

ptr1="ptreee765885"
ptr2="hdjfhdjh@@@@"
str1=re.compile(r'[a-zA-Z0-9]+')

result=str1.match(ptr1)
result1=str1.match(ptr2)

if str1.match(ptr2):
print (" string matches %s",ptr2)
else:
print (" string not matches pattern %s",ptr2)
4
  • Both will match expectedly..whats your goal? Commented Feb 9, 2016 at 15:52
  • Both strings have sequences of alphanumerics, which is all you are testing for. Commented Feb 9, 2016 at 15:52
  • have you tried using a debug function? Commented Feb 9, 2016 at 15:56
  • how to check for the string having '- ',',' whitspace and | Commented Feb 10, 2016 at 10:45

2 Answers 2

1

You will need to add the $ to match the end of the string:

str1=re.compile(r'[a-zA-Z0-9]+$')

You should also include the ^ character at the beginning to match the beginning of the string if you need the entire string to match:

str1=re.compile(r'^[a-zA-Z0-9]+$')

That will only match if the entire string matches that selection.

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

Comments

0

Python re.match is not the same as regex_match in C++ std::regex or Java String#matches method, it only searches for a match at the start of the string.

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance.

Thus, to fail a match with your ptr2, the regex should only have a $ (or \Z) anchor at the end if you are using re.match:

See IDEONE demo:

import re
ptr2="hdjfhdjh@@@@"
str1=re.compile(r'[a-zA-Z0-9]+$')
if str1.match(ptr2):
   print (" string matches %s",ptr2)
else:
   print (" string not matches pattern %s",ptr2)
# => (' string not matches pattern %s', 'hdjfhdjh@@@@')

If you plan to use re.search, you need both ^ and $ anchors to require a full string match:

import re
ptr2="hdjfhdjh@@@@"
str1=re.compile(r'^[a-zA-Z0-9]+$')
if str1.search(ptr2):
   print (" string matches %s",ptr2)
else:
   print (" string not matches pattern %s",ptr2)

Another demo

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.