Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 views
in Technique[技术] by (71.8m points)

c# - RegEx - reusing subexpressions

Say I have a regex matching a hexadecimal 32 bit number:

([0-9a-fA-F]{1,8})

When I construct a regex where I need to match this multiple times, e.g.

(?<from>[0-9a-fA-F]{1,8})s*:s*(?<to>[0-9a-fA-F]{1,8})

Do I have to repeat the subexpression definition every time, or is there a way to "name and reuse" it?

I'd imagine something like (warning, invented syntax!)

(?<from>{hexnum=[0-9a-fA-F]{1,8}})s*:s*(?<to>{=hexnum})

where hexnum= would define the subexpression "hexnum", and {=hexnum} would reuse it.

Since I already learnt it matters: I'm using .NET's System.Text.RegularExpressions.Regex, but a general answer would be interesting, too.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

RegEx Subroutines

When you want to use a sub-expression multiple times without rewriting it, you can group it then call it as a subroutine. Subroutines may be called by name, index, or relative position.

Subroutines are supported by PCRE, Perl, Ruby, PHP, Delphi, R, and others. Unfortunately, the .NET Framework is lacking, but there are some PCRE libraries for .NET that you can use instead (such as https://github.com/ltrzesniewski/pcre-net).

Syntax

Here's how subroutines work: let's say you have a sub-expression [abc] that you want to repeat three times in a row.

Standard RegEx
Any: [abc][abc][abc]

Subroutine, by Name
Perl: ????(?'name'[abc])(?&name)(?&name)
PCRE: (?P<name>[abc])(?P>name)(?P>name)
Ruby: ??(?<name>[abc])g<name>g<name>

Subroutine, by Index
Perl/PCRE: ([abc])(?1)(?1)
Ruby: ?????????([abc])g<1>g<1>

Subroutine, by Relative Position
Perl: ????([abc])(?-1)(?-1)
PCRE: ([abc])(?-1)(?-1)
Ruby: ??([abc])g<-1>g<-1>

Subroutine, Predefined
This defines a subroutine without executing it.
Perl/PCRE: (?(DEFINE)(?'name'[abc]))(?P>name)(?P>name)(?P>name)

Examples

Matches a valid IPv4 address string, from 0.0.0.0 to 255.255.255.255:
((?:25[0-5])|(?:2[0-4][0-9])|(?:[0-1]?[0-9]?[0-9])).(?1).(?1).(?1)

Without subroutines:
((?:25[0-5])|(?:2[0-4][0-9])|(?:[0-1]?[0-9]?[0-9])).((?:25[0-5])|(?:2[0-4][0-9])|(?:[0-1]?[0-9]?[0-9])).((?:25[0-5])|(?:2[0-4][0-9])|(?:[0-1]?[0-9]?[0-9])).((?:25[0-5])|(?:2[0-4][0-9])|(?:[0-1]?[0-9]?[0-9]))

And to solve the original posted problem:
(?<from>(?P<hexnum>[0-9a-fA-F]{1,8}))s*:s*(?<to>(?P>hexnum))

More Info

http://regular-expressions.info/subroutine.html
http://regex101.com/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...