J Szum
J Szum

Reputation: 515

Regex match by occurrences of certain characters

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

Answers (1)

Gurmanjot Singh
Gurmanjot Singh

Reputation: 10360

Try this Regex:

^(?!.*pp.*kk)[kp]+$

Click for Demo

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 string

Upvotes: 2

Related Questions