Matching wwR ("acddca") using regex example in C #

I'm a complete noob on regexes. I read them, but I still don't get them, for example I don't even know what the "-" sign means. Can we do example one and walk through it perhaps? How do we do it?

a busy cat

Basically this syntax is a string added by its backwards.

This should match:

abccba
bCaaCb

      

It doesn't have to match:

lebronnorBeL
bcAacb

      

Many thanks for your help!

+3


source to share


2 answers


As far as I know, RegEx doesn't play with patterns like this.

My workaround would look like this:



private bool isMirrorLikeString(string content) {
    for (int i = 0; i < (int)(content.Length / 2); i++) {
        if (content[i] != content[content.Length - 1 - i]) return false;
    }
    return true;
}

      

+1


source


In theory, the language in question has no context, so it cannot be described using a regular expression. However, the regex engine in languages ​​and in the library introduces features that make them more powerful than theoretical regex.

In this case, it simply asks you to locate the palindrome string, except that the total length of the string is always even.

We can take the regex from this answer and modify it:

(?<N>[01])+(?<-N>\k<N>)+(?(N)(?!))

      



I omitted the part .?

that allows an odd-length palindrome and change .

internally (?<N>.)

to fit the question)

  • (?<N>[01])+

    grabs and pushes a character onto the "stack" N

    .
  • (?<-N>\k<N>)+

    popped off the "stack" N

    (note <-N>

    ) when the item on top of the stack matches the current character ( \k<N>

    this is a normal backreference for capture group N).
  • (?(N)(?!))

    checks if there is anything else left on the stack N

    then fail and return.

Note that this regex is unique to the .NET engine due to the balancing of the group function in .NET. Perl and PCRE can also match the language in question, but with a different function (normal call).

0


source







All Articles