David Masip
David Masip

Reputation: 2491

At least 2 different letters in regex

What regex checks if there are at least two different letters in a string?

For instance:

Upvotes: 0

Views: 714

Answers (2)

no_one
no_one

Reputation: 163

If "different" just means "separate" and you only want letters from the English alphabet, this should do the trick. The following regex will find match strings with at least two English letters:

.*[a-zA-Z].*[a-zA-Z].*
  • .* matches 0 or more of any character except a newline character
  • [a-zA-Z] matches any character in English alphabet case-insensitively

If you want a regex that matches strings with at least two different English letters, this one satisfies that criteria:

.*([a-zA-Z])(?!\1).*([a-zA-Z]).*
  • (regex stuff) creates a "capturing group" whose result is referenceable by later tokens
  • (?!\1) is a negative lookahead that asserts no capturing group can match the result of the first capturing group
  • \1 is a backreference that matches the result of capturing group #1

You can test these here: https://www.regextester.com/

Upvotes: 1

Bohemian
Bohemian

Reputation: 425033

You need exactly 2 chars, where the second is not the first:

^(.)(?!\1).$

See live demo.

Breakdown:

  • ^ start
  • (.) captures the first char as group 1
  • (?!\1) a negative look-ahead that asserts the following character is not the same as the first character
  • . a character
  • $ end

To restrict the match to only letters (upper or lower case):

^([a-zA-Z])(?!\1)[a-zA-Z]$

Upvotes: 1

Related Questions