正则表达式 - 重用SUBEX pressions [英] RegEx - reusing subexpressions

查看:114
本文介绍了正则表达式 - 重用SUBEX pressions的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能是一个相当n00bish问题:说我有一个正则表达式匹配一个十六进制的32位号码:

Probably a rather n00bish question: 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})

我必须每次都重复SUBEX pression的定义,或者是有办法的名字和重用呢?

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

我想像类似(警告,发明了语法!的)

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

其中, hexnum = 将定义SUBEX pressionhexnum,而{= hexnum}将重新使用它。

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

既然我已经学会了它的问题:我使用的是.NET的 System.Text.RegularEx pressions.Regex ​​,而是一个普遍的答案将是很有意思,太

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

推荐答案

为什么不这样做,不是真的较短,但有点更易于维护。

Why not do something like this, not really shorter but a bit more maintainable.

String.Format("(?<from>{0})\s*:\s*(?<to>{0})", "[0-9a-zA-Z]{1,8}");

如果你想要更多的自我记录codeI将指定数量的正则表达式字符串到适当命名的常量的变量。

If you want more self documenting code i would assign the number regex string to a properly named const variable.

这篇关于正则表达式 - 重用SUBEX pressions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆