Regex matches a string of unique characters

Here is my regex:

((GO)( [AZ])+) 

I want each letter to appear no more than once, unfortunately, it does not work properly, because this input:

 GO ABCC 

returns true, but returns false.

+6
source share
3 answers

You can use this regex:

 ^(GO(?: ([AZ])(?!.*\2))+)$ 

RegEx Demo

+5
source

Your regex:

 GO(?:([AZ])(?!.*\1))+$ 
  • Corresponds to the letter GO , and then:
  • Any AZ character, from zero to infinite time
  • the statement for each character encountered that the same character does not match any ( . ) subsequent character before the next line break ( $ ).

The key to this last step, which is all you were missing, is the negative back side of zero length : (?!.*\1)

+4
source

You can use the following regular expression:

 ^GO (?:([AZ])(?!.*\1)\s*)*$ 

It will correspond to all that:

  • starts with GO<space>
  • contains only letters ( [AZ] ) which:
    • can be separated by any sequence of blank characters, but:
    • perhaps never seen before.

See working on regex101 !


Matching examples:

 GO ABC GO ABC GO ABCGO 

Examples of inconsistencies:

 ABC GO AAA 
+1
source

Source: https://habr.com/ru/post/976892/


All Articles