12

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
Matthew
  • 21,467
  • 5
  • 66
  • 95
LeBron23
  • 195
  • 1
  • 7
  • 1
    Is n known? Or is it any number as long as the number is the same for all the letters? – Robbert Apr 23 '15 at 21:23
  • @Robbert sounds like the latter – RaGe Apr 23 '15 at 21:25
  • Related: [Capturing Quantifiers and Quantifier Arithmetic](http://stackoverflow.com/questions/23001137/capturing-quantifiers-and-quantifier-arithmetic) – HamZa Apr 23 '15 at 21:32
  • What's the point? It's not a regular language, regular expressions is the wrong tool for the job. You might be able to coerce it to work by using nonstandard/ridiculous solutions but again... what's the point... – Jeff Mercado Apr 23 '15 at 21:32
  • 1
    @JeffMercado: The point is to determine what’s written in the question, I suppose: *“How powerful is the modern regex in the hierarchy?”* – Ry- Apr 23 '15 at 21:37
  • @minitech Yes I'm aware of that. Heck, we could probably even use modern engines to (correctly) parse HTML, but it still isn't the right tool for such a task. – Jeff Mercado Apr 23 '15 at 22:13

1 Answers1

13

.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.

Ry-
  • 199,309
  • 51
  • 404
  • 420