1

a sentence needs to contain 1 or more instances of 'a', exactly 1 instance of 'b' and 0 or more instances of 'c' my expression is a+bc* it works for strings like 'abc' 'ab' 'aabcc' which is all fine but it also works when i have multiple b's like 'abbc' which it shouldn't. How do i get it to work when theres only 1 'b'

Here is my full code

import re
qq = re.compile('a+bc*')
if qq.match('abb') is not None:
    print("True")
else:
    print('False')

which should produce False

Omar
  • 55
  • 4
  • What is your desired output from your logic? A `True` or `False` depending on your criteria? Since you have some code, sharing it with us will help us correct your problem. – jpp Apr 25 '18 at 16:58
  • What code did you use to check this? Please post the code as well – Tarun Lalwani Apr 25 '18 at 16:59
  • Take a look at this [pythex](https://pythex.org/?regex=a%2Bbc*&test_string=abbc&ignorecase=0&multiline=0&dotall=0&verbose=0) it shouldn't capture all of `'abbc'` – bphi Apr 25 '18 at 17:05
  • `a+bc*` matches `abb` because there is one `a` followed by one `b`. So it has matched after the second character. The second `b` is ignored. – Tony Tuttle Apr 25 '18 at 17:05
  • The `re.match` method checks only the beginning of the string. To describe all the string until the end you have to add `$` in your pattern. – Casimir et Hippolyte Apr 25 '18 at 17:06
  • yeah even regex101 does that but if you run the code above in a compiler it will return True – Omar Apr 25 '18 at 17:07
  • @CasimiretHippolyte that worked! thanks sir – Omar Apr 25 '18 at 17:08
  • You can also use the `re.fullmatch` method (since the 3.4 version). – Casimir et Hippolyte Apr 25 '18 at 17:24

1 Answers1

2

Use qq=re.compile(r'^a+bc*$'). The ^ means match at start and $ means match at the end.

You want to match the pattern to the full string and not a part of it. That is why you need the ^ and $ in this case

Tarun Lalwani
  • 142,312
  • 9
  • 204
  • 265
Null
  • 36
  • 3