How do I include characters, space and maximum two consecutive character in dart?

Viewed 39

Does anyone know how to use a regular expression in Dart, where maximum two consecutive characters allow.

Example :

aabc //allow

aaabc // not allow

aabc aabc // not allow same string

aabcde //allow

abs cdd ert fgg fgy df //allow

I tried this but it won't work:

([A-Za-z])?!.*\1

([a-zA-Z])-?\1-?\1-?\1-?\1

^(?:([A-Za-z])(?!.\1))$

1 Answers

If you want to match chars A-Za-z, you can make use of word boundaries and use 2 negative lookaheads.

The first lookahead excludes matching 3 of the same chars in a row, the second lookahead excludes 2 times the same "word" where a word is identified by the word boundaries.

^(?!.*([A-Za-z])\1\1)(?!.*\b([A-Za-z]+)\b.*\2).+

Explanation

  • ^ Start of string
  • (?!.*([A-Za-z])\1\1) Negative lookahead, assert that to the right is not a char A-Za-z directly followed by 2 times the same char using a backreference
  • (?!.*\b([A-Za-z]+)\b.*\2) Negative lookahead, assert that to the right is not 1+ chars A-Za-z surrounded by a word boundary, and then find that same "word" again
  • .+ Match 1+ chars

See a regex demo.

Related