正则表达式量词中的反向引用 [英] Backreference in Regular Expression Quantifier
问题描述
我有一个字符串,其中包含一个长度为以下字段的标题.
I have a string that contains a header with a length of the following field.
示例:
fillerfillerCA20 abcdefghijklmnopqrst CA5 zyxwvfillerfiller
我需要找到两个值:abcdefghijklmnopqrst和zyxwv
I need to find the two values: abcdefghijklmnopqrst and zyxwv
我打算使用反向引用来获取量词的长度:
I was going to use a backreference to get the length for the quantifier:
(?i)ca(?<length>\d+?)\x20.{\k<length>}\x20?
但显然,不支持在量词中使用反向引用.
but apparently, using a backreference in a quantifier is not supported.
我怎样才能做到这一点?
How can I accomplish this?
推荐答案
不是一步到位.正则表达式不能是自引用的.它们首先被构建,然后被使用.一旦构建了正则表达式,就无法重新构建/扩充.
Not in one step. Regular expressions cannot be self-referential. They are first built, and then used. No re-building/augmenting is possible once the regex is built.
您可以像之前一样匹配长度信息,并在第二步中使用它,同时评估匹配.
You can match the length info as you already do and use it in a second step, while evaluating the matches.
先发制人的评论:我知道可以用 "(.)\1"
来匹配同一个字符两次.不过,这不是我所说的自我参照".
Preemptive comment: I know that one can do "(.)\1"
to match the same character twice. This is not what I mean with "self-referential", though.
这篇关于正则表达式量词中的反向引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!