开发者

Using a Regex Back-reference In a Repetition Construct ({N})

I need to match a string that is prefixed with an a开发者_C百科cceptable 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")


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜