L = {a ^ n ^ t | n + m = k, n, m> = 0} with regular expression in C #

I want to create the following language:

L={a^nb^m| n+m=k ,n,m>=0}

for a constant k.

I am using a Regexnamespace class System.Text.RegularExpressions.

The best solution I have now is:

public void Match(string input, int k)
{
    Regex regex = new Regex(@"a*b*");
    Match match = regex.Match(input);
    if(match.Length==k)
        Console.WriteLine("Successfully");
    else
        Console.WriteLine("Don't match");
}

For k=5successfully used the following inputs:

"aaabb"
"aabbb"
"aaaaa"

This, for example, is not:

"aaabbb"
"ab"

What is the most elegant way to achieve this?

+4
source share
2 answers

You can achieve this using a forward-looking forecast.

For k = 5

/^(?=.{5}$)a*b*$/
  • (?=.{5}$)Put your eyes forward. Ensures that the string contains only 5 characters.

  • a*b*matches zero or more events a, followed by zero or more casesb

Regex Demo

Test

public static void Match(string input, int k)
{
    Regex regex = new Regex(@"^(?=.{"+k+"}$)a*b*$");
    Console.WriteLine(regex.IsMatch(input));

}

Match("aaabb", 5);
=> True
Match("aaabbb", 5);
=> False
+6

nu11p01n73R look-ahead, , ( , Kleene).

. . , k = 5:

aaaaa|aaaab|aaabb|aabbb|abbbb|bbbbb

, :

aaa(aa|ab|bb)|(aa|ab|bb)bbb

. k , 2k + 1 .

k = 5:

, .

+1

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


All Articles