Better explained with examples:
- HHH
- HHHH
- HHHBBHHH
- HHHBH
- BB
- HHBH
I need to come up with a regexp that matches only 3 H’s or a multiple of 3 H’s (so 6, 9, 12, … H’s are ok as well) and 5 H’s are not ok. And if possible I don’t want to use Perl regexps.
So for the input above the regexp would match (1), (3) and (6) only.
I’m just starting with regular expressions here so I don’t exactly know how I’m supposed to approach this.
edit
Just to clear something up:, an H can only be in one group of 3 H’s. The group of 3 H’s might be HHH or HHBH.
That’s why in example 2 above it is not a match because the last H is not in a group of 3 H’s. And you can’t take the last 3 H’s in a group because the middle 2 H’s have already been inside a group before.
You can use the following regular expression:
It matches any string which contains in total 3 H or any multiple of 3. In between there might be any other character.
Explanation:
By repeating the subpattern
[^H]*Hthree times we make sure that there are indeed 3Hincluded,[^H]*allows any separating characters.Note: use either
egrepor run grep with additional argument-E.