Robert Androsz
Robert Androsz

Reputation: 211

Regular expression matching both conditions but on separate parts of string

I have the following regexes:

  1. ([JQKA])\1

  2. ([2-9TJQKA])\1

I would like to check string with length of 5 if both of regexes matches together - but on separate characters.

So:

If I have a string of 2233 - it should not match because it does not meet condition of Regex 1 and is meeting condition of Regex 2

If I have a string of 33QQ2 - it should match because QQ matches Regex 1 and 33 matches Regex 2

If I have a string AQQ44 - it should match because QQ Regex 1 and 44 matches Regex 2

If I have a string AAKQQ - it should match because AA Regex 1 and QQ matches Regex 2

If I have a string QQ234 - it should not match. Even when it matches Regex 1 and Regex 2 condition with same QQ, I want second condition to validate other part of string than first so after it matches Regex 1 - it does not find part that match Regex 2.

Upvotes: 2

Views: 142

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627536

You may use

/^(?=.{5}$).*(?:([JQKA])\1.*([2-9TJQKA])\2|([2-9TJQKA])\3.*([JQKA])\4)/

See the regex demo. You may replace . in the lookahead pattern with [A-Z0-9] if you only allow uppercase letters or digits in the string (i.e. (?=.{5}$) => (?=[A-Z0-9]{5}$)).

Details

  • ^ - start of string
  • (?=.{5}$) - total string length must be 5 chars other than line break chars
  • .* - any 0 or more chars other than line break chars as many as possible
  • (?:([JQKA])\1.*([2-9TJQKA])\2|([2-9TJQKA])\3.*([JQKA])\4) - a non-capturing group matching either of
    • ([JQKA])\1.*([2-9TJQKA])\2 - Pattern 1 followed with any 0 or more chars other than line break chars, as many as possible and the Pattern 2
    • | - or
    • ([2-9TJQKA])\3.*([JQKA])\4 - Pattern 2 followed with any 0 or more chars other than line break chars, as many as possible and the Pattern 1

Upvotes: 2

Related Questions