tags:

views:

32

answers:

1

I need to match a string that is prefixed with an acceptable length for that string.

For example, {3}abc would match, because the abc part is 3 characters long. {3}abcd would fail because abcd is not 3 characters long.

I would use ^\{(\d+)\}.{\1}$ (capture a number N inside curly braces, then any character N times) but it appears that the value in the repetition construct has to be a number (or at least, it won’t accept a backreference).

For example, in JavaScript this returns true:

/^\{(\d+)\}.{3}$/.test("{3}abc")

While this returns false:

/^\{(\d+)\}.{\1}$/.test("{3}abc")

Is this possible to do in a single regex, or would I need to resort to splitting it into two stages like:

/^\{(\d+)\}/.test("{3}abc") && RegExp("^\\{" + RegExp.$1 + "\\}.{" + RegExp.$1 + "}$").test("{3}abc")

+2  A: 

Regular expressions can't calculate, so you can't do this with a regex only.

You could match the string to /^\{(\d+)\}(.*)$/, then check whether len($2)==int($1).

In Python, for example:

>>> import re
>>> t1 = "{3}abc"
>>> t2 = "{3}abcd"
>>> r = re.compile(r"^\{(\d+)\}(.*)$")
>>> m1 = r.match(t1)
>>> m2 = r.match(t2)
>>> len(m1.group(2)) == int(m1.group(1))
True
>>> len(m2.group(2)) == int(m2.group(1))
False
Tim Pietzcker
Ah, I figured as much. Thanks for confirming my suspicions.
davecardwell