Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match string of unique characters

Tags:

java

regex

unique

Here is my regular expression:

((GO)( [A-Z])+)

I want every letter to appear at most once, unfortunately it isn't working properly, because this input:

GO A B C C

return true, but should return false.

like image 541
Aleksander Mielczarek Avatar asked Oct 17 '14 21:10

Aleksander Mielczarek


3 Answers

You can use this regex:

^(GO(?: ([A-Z])(?!.*\2))+)$

RegEx Demo

like image 69
anubhava Avatar answered Sep 20 '22 11:09

anubhava


Your regex is:

GO(?:([A-Z])(?!.*\1))+$
  • Matches the literal GO, followed by:
  • Any character A-Z, from zero to infinite times
  • asserting, for each character encountered, that the same character does not match any (.) subsequent character before the next line break ($).

The key to that last step, which is all you were missing, is the zero-length negative lookahead: (?!.*\1)

like image 31
drew moore Avatar answered Sep 20 '22 11:09

drew moore


You could use the following regex:

^GO (?:([A-Z])(?!.*\1)\s*)*$

It will match anything that:

  • starts with GO<space>
  • contains only letters ([A-Z]) that:
    • may be separated by any sequence of blank characters, but:
    • may not have ever been seen before.

See it working on regex101!


Sample matching cases:

GO A B C
GO ABC
GO A B C G O

Sample non-matching cases:

A B C
GO A A A
like image 43
ccjmne Avatar answered Sep 22 '22 11:09

ccjmne