By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,851 Members | 1,133 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,851 IT Pros & Developers. It's quick & easy.

Regular expression doubt

P: 1
problem : atleast 2 char string wherein 1 char should be between a-k , second char should a number divisible by 3 and then any digit or character.

Expand|Select|Wrap|Line Numbers
  1. import re
  2. patt=re.compile(r"[a-k][0369][a-zA-Z0-9#]*")
  3. m=patt.search("aaa9#")
  4. if(m!=None):
  5.     print("Matched")
  6. else:
  7.     print("Not Matched")
Why does above program gives Matched?
2 Weeks Ago #1
Share this Question
Share on Google+
3 Replies


Expert 100+
P: 612
There is an old saying, "you have to solve a problem. You decide to use regular expressions. Now you have two problems." So unless you are required to use regular expressions, it is easier and more straight forward to use if statements
Expand|Select|Wrap|Line Numbers
  1. ## atleast 2 char string
  2. test_string="aaa9#"
  3. if len(test_string > 1):
  4.     ## wherein 1 char should be between a-k
  5.     ## I assume this means the first character
  6.     if "a" <= test_string[0] <= "k":
  7.         ## second char should a number divisible by 3
  8.  
  9.         ## *****Your test string fails here*****
  10.         if test_string[1].isdigit() and 0 == int(test_string[1]) % 3:
  11.             print("Matched") 
2 Weeks Ago #2

Rabbit
Expert Mod 10K+
P: 12,342
Because the substring "a9" matches your regex. Nothing in your regex says the whole string has to conform.
2 Weeks Ago #3

Expert 100+
P: 1,026
@Rabbit is right, and maybe a bit 'off-topic', but yesterday I was reading this on stackoverflow. which might be of interest. it's about using regular expressions 😉
1 Week Ago #4

Post your reply

Sign in to post your reply or Sign up for a free account.