Reputation: 515
Assume the string contain only two characters - k and p. What regex expression will match the strings where all pairs of k occur before pairs of p?
I have the following expression so far, but it does not catch all the cases (the ones with repeated k and ends with kk):
^(k*|k+p{1}|k{1}p+)[kp]*(kpkk|pk|pp|kp)$
Example of strings:
k // match
kk // match
kkkkpp // match
kkppk // match
ppppkkp // no match
kppppppkk // no match
kppk // match
kpkpkpkpkp // match
kppkpkk // match
Upvotes: 1
Views: 83
Reputation: 10360
Try this Regex:
^(?!.*pp.*kk)[kp]+$
Explanation:
^
- start of the string(?!.*pp.*kk)
- negative lookahead to make sure that the current match should not have any case where kk
comes after pp
[kp]+
- matches 1+ occurrences of either k
or p
$
- end of the stringUpvotes: 2