A regular expression that does not guarantee the repetition of a character

I need to make sure that the input line matches the following rules:

  • It should contain only uppercase characters.
  • The character NO must be repeated in the string. eg. ABCA is invalid because "A" is repeated.

In the case of uppercase [AZ] should be fine. But I am lost in how to ensure the absence of duplicate characters.

Can anyone suggest a method using regular expressions?

+3
source share
6 answers

You can do this with .NET regular expressions, although I would advise him:

string s = "ABCD";
bool result = Regex.IsMatch(s, @"^(?:([A-Z])(?!.*\1))*$");

, A-Z :

bool result = s.Cast<char>().Distinct().Count() == s.Length;

, , , .

+6

, . , , - , - .

. .

+2

, ? - ([A-Z])?.*?([^A-Z]|\1)

+2

.

  string pattern = @"^(?!.*(.).*\1)[A-Z]+$";
  string s1 = "ABCDEF";
  string s2 = "ABCDAEF";
  string s3 = "ABCDEBF";
  Console.WriteLine(Regex.IsMatch(s1, pattern));//True
  Console.WriteLine(Regex.IsMatch(s2, pattern));//False
  Console.WriteLine(Regex.IsMatch(s3, pattern));//False

\1 . , lookahead , - .

+2

This is not a regular expression and will be slow, but you can create an array of the contents of the string and then iterate through the array comparing n to n ++

= Waldo

0
source

This can be done using the callback function.

I am a Java program, so I will show you how to do it in Java (for C #, see here ).

final Pattern aPattern = Pattern.compile("([A-Z]).*\\1");
final Matcher aMatcher1 = aPattern.matcher("ABCDA");
System.out.println(aMatcher1.find());
final Matcher aMatcher2 = aPattern.matcher("ABCDA");
System.out.println(aMatcher2.find());

There is a regular express ([A-Z]).*\\1translating to anything between 'A' to 'Z' as group 1 ('([A-Z])') anything else (.*) and group 1.

Use $1for C #.

Hope this helps.

0
source

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


All Articles