Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching a^n b^n c^n (for example “aaabbbccc”) using regular expressions in C#

Tags:

c#

regex

You can easily use regex to verify a regular language. My question is can you use it to verify a context-sensitive language? How powerful is the modern regex in the hierarchy?

How would you go about to create a regex that checks for strings that match a^n b^n c^n?

The following cases should match:

abc
aabbcc
aaabbbccc

The following cases should not match:

abbc
aabbc
aabbbccc
like image 285
LeBron23 Avatar asked Apr 23 '15 21:04

LeBron23


1 Answers

.NET provides balancing groups that you should be able to use to do this; something like:

^(?<n>(?<o>a))*(?<-n>b)*(?<-o>c)*(?(n)(?!))(?(o)(?!))$

Increment n and o for each a, decrement n for each b and then o for each c, then fail the match ((?!)) if either counter is still greater than zero.

like image 179
Ry- Avatar answered Oct 13 '22 23:10

Ry-