Using a Regex Back-reference In a Repetition Construct ({N}) -
I need to match that string which is the prefix with the length acceptable to that string.
For example, {3} ABC
will match, because ABC
part 3
characters is long. {3} ABCD will fail
because abcd
is not 3
character long. Use
I ^ \ {(\ d +) \}. {\ 1} $
(Capture a number N
inside curly braces, then any character N
bar) but it appears that the duplication The value of the construction should be a number (or at least, it will not accept a back break).
For example, this is true in javascript:
/ ^ \ {(\ d +) \}. {3} $ / Test ("{3} ABC")
While it returns false:
/ ^ \ {(\ d +) \}. {\ 1} $ / / Exam ("{3} ABC")
Is it possible to do a single regex, or I have to split it into two steps:
/ ^ \ {(\ d +) \} / Testing ("{3} ABC") & amp; Amp; RegExp ("^ \\ {" + RegExp. $ 1 + "\\}. {" + RegExp. $ 1 + "} $"). Exam ("{3} ABC")
Regular expression can not be calculated So, you can not do this just with a regex.
You can match the string to / ^ \ {(\ d +)}}. (. *) $ /
, then check whether len ($ 2) == int ($ 1)
In Python, for example:
& gt; & Gt; & Gt; Import re & gt; & Gt; & Gt; T1 = "{3} ABC" & gt; & Gt; & Gt; T2 = "{3} ABCD" & gt; & Gt; & Gt; R = re.compile (r "^ \ {(\ d +) \} (. *) $") >> Gt; & Gt; & Gt; M1 = R. Mitch (T1) & gt; & Gt; & Gt; M2 = R. Mitch (T2) & gt; & Gt; & Gt; Lane (m1.group (2)) == int (m1.group (1)) true & gt; & Gt; & Gt; LAN (m2.group (2)) == int (m2.group (1)) false
Comments
Post a Comment