-1

Ex: I want to ensure that a string must contain A, B, C, D

  test strings:
  "ABCDF" will be true 
  "AACDF" will be false (it not contains 'B') 
  "AABCDFG" will be true (it allows duplicated words)   

Thanks to everyone!

Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
Antonio Steve
  • 33
  • 1
  • 4
  • Have you tried anything? Do some research, try it out, we will help if you demonstrate some effort. – Nic3500 Jun 10 '18 at 05:35
  • Possible duplicate of [Regex to match only letters](https://stackoverflow.com/questions/3617797/regex-to-match-only-letters) – Anon Jun 10 '18 at 05:39
  • yes, Nic3500, I read and try some such as (*.[abcd]{1,}.*){4,} , it can not exclude the string like 'aabbff' – Antonio Steve Jun 10 '18 at 07:23
  • @antonio-steve to combat that look into how anchoring works... – Anon Jun 11 '18 at 20:46

1 Answers1

0

If you want a regex matching a single word containing 4 particular letters (in some bigger text), you can use:

(?=\w*A)(?=\w*B)(?=\w*C)(?=\w*D)\w+

It contains 4 positive lookups. Each of them looks for A, B, C and D, respectively, after a number of word chars (possibly 0). Then there is the actual matching part - a sequence of word chars.

You should use also g (global) option, to match all such words.

Another possibility is that you want to verify the whole string (something like password criteria verification). Then the regex can be:

(?=.*A)(?=.*B)(?=.*C)(?=.*D).+

The differences are that:

  • Each lookahead looks for the particular char after any number of any chars (instead of word chars).
  • The matching part contains also any chars (matches the whole string).
  • g option is not needed.
Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41