1

I am trying to make a regex that will match a number of x's that is a power of two. I am using JavaScript. I tried this one:

^(x\1?)$

but it doesn't work. Shouldn't the \1 refer to the outer parathesis so it should match xx, and therefore also xxxx, etc.?

I tried a simpler one that I thought would match x and xx:

^((x)|(\2{2}))$

but this only matches x.

What am I doing wrong?

Édouard Lopez
  • 40,270
  • 28
  • 126
  • 178
Joe
  • 7,922
  • 18
  • 54
  • 83

1 Answers1

2

You can't do "recursive backreferences". At least, it is not so easy.

I'm no sure that you need recuresive regular expressions here. May be you could just count number of the characters in the string and check if it is equal to a power of two?

But if you really need recursive regular expressions (I'm almost sure, you don't), you can check this question:

and this blog

Community
  • 1
  • 1
Igor Chubin
  • 61,765
  • 13
  • 122
  • 144
  • Can I count the number of characters using regular expression? – Joe Jan 02 '14 at 17:00
  • Also, how about my second, simpler regex. Do you know what is wrong with that? – Joe Jan 02 '14 at 17:01
  • 1
    The second regex is wrong because you make alternatives in it and you have the ()-part in one alternative and the backreference in the other. That will not work. You can use backreferences if they matched. – Igor Chubin Jan 02 '14 at 17:11
  • Can I refer to that backreference at all from there? – Joe Jan 02 '14 at 18:40
  • @Joe: Sure. But only to that that are matched – Igor Chubin Jan 02 '14 at 18:47
  • I'm sorry I don't understand. Could you explain, maybe with an example of how to do it? – Joe Jan 02 '14 at 18:49
  • @Joe: For example, this will work `(a|(b)\2)` and this `((a)|b\2)` will not, because `(a)` belongs to another alternative, therefore will not be matched. – Igor Chubin Jan 02 '14 at 18:51