Using Regex Backlinks in a Repeat Construction ({N})

I need to match a string that has a valid length prefix for this string.

For example, {3}abc will match because the abc part is 3 . {3}abcd will fail because abcd no longer than 3 .

I would use ^\{(\d+)\}.{\1}$ (grab the number N inside the braces, then any character N times), but it turns out that the value in the repetition construct should be a number (or at least , accept the back link).

For example, in JavaScript, this returns true:

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

So far, this returns false:

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

Is it possible to do this in one regular expression, or do I need to resort to splitting it into two stages, for example:

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

+4
source share
1 answer

Regular expressions cannot be evaluated, so you cannot only do this with regular expressions.

You can match the line with /^\{(\d+)\}(.*)$/ , and then check 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 
+2
source

All Articles