开发者

Use Pattern-Templates inside Regex?

I'm wondering if it's possible to use something like custom Pattern Templates inside Regular Expressions. A simple example:

# this regex
^1xyz2xyz3xyz4$
# matches this string
"1xyz2xyz3xyz4"

As one can see, I have to use "xyz" three times, so my question is: can I define a template once for "xyz" and then use the templa开发者_高级运维te name in the rest of the regex?


In Perl and PCRE you can use (?(DEFINE)...) blocks to declare named groups and then call them as named regexes:

my $re = qr{
    (?(DEFINE) (?<tmp> xyz )  )
    ^ 1 (?&tmp) 2 (?&tmp) 3 (?&tmp) 4  $
}x;

print "1xyz2xyz3xyz4" =~ $re;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜