-3

I am currently going through pythonchallenge.com, and now trying to make a code that searches for a lowercase letter with exactly three uppercase letters on both side of it. Then I got stuck on trying to make a regular expression for it. This is what I have tried:

import re
#text is in https://pastebin.com/pAFrenWN since it is too long
p = re.compile("[^A-Z]+[A-Z]{3}[a-z][A-Z]{3}[^A-Z]+")
print("".join(p.findall(text)))

This is what I got with it: dqIQNlQSLidbzeOEKiVEYjxwaZADnMCZqewaebZUTkLYNgouCNDeHSBjgsgnkOIXdKBFhdXJVlGZVme gZAGiLQZxjvCJAsACFlgfe qKWGtIDCjn

I later searched for the solution, which had this regular expression:

p = re.compile("[^A-Z]+[A-Z]{3}([a-z])[A-Z]{3}[^A-Z]+")

So there is a bracket around [a-z], and I couldn't figure out what difference it makes. I would like some explanation on this.

0''
  • 93
  • 4
  • `{3}` is the previous expression has to be found 3 times. `[A-Z]{3}` is the same than `[A-Z][A-Z][A-Z]` – DanB Dec 23 '18 at 03:39
  • @DanB The OP isn't talking about `{3}`; they are referring to `[a-z]` Vs `([a-z])`. – Tedinoz Dec 23 '18 at 03:52

1 Answers1

0

Use Parentheses for Grouping and Capturing By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex.

https://www.regular-expressions.info/brackets.html

Basicly the regex engine can find a list of strings matching the whole search pattern, and return you the parts inside the ().

Hainan Zhao
  • 1,962
  • 19
  • 19