0

I'm new to regex and I was wondering why this doesn't work and what would be the simplest way to solve this. The code is in python 3. Alternatives are more than welcome since I have to learn as many ways as possible to solve this problems. Thanks in advance! See my explanation bellow:

my_string = 'This is a dog, a very cute one'
re.findall('This is a dog',my_string)

Assume I want to capture a sentence like 'This is Dog, a very cute one' (same sentence without the "a").

#This works
print(re.findall('This is a?dog','This is Dog, a very cute one',flags=re.I))

I expected that the phrase "This is a" could occur zero or one times like I did with the a. So grouping with () and placing ? would be a good option.

print(re.findall('(This is a)? dog',my_string))

Why the the ? is not working for the group and is working just for a single character like "a" ?

Tomas -
  • 49
  • 7
  • It works as expected, but you probably did not expect this. Use a non-capturing group. – Wiktor Stribiżew Jan 24 '20 at 13:58
  • Hahah okay, you're right. Anyways, I guess using a non-capturing group would be: print(re.findall('This is a? dog',my_string)) But this will fail a well. Capturing groups works for | but not for other operators like the ? ? – Tomas - Jan 24 '20 at 14:02

0 Answers0