正则表达式和从右到左的匹配代码
使用正则表达式有点麻烦,我在字符串
CODE4:CODE3:CODE2:CODE1
中有 4 个代码,除了 CODE1 之外,每个代码都是可选的,
所以我可以有 ab:bc:de:fg
或
bc::fg
ab
: ::fg
在上述 CODE1 = fg dnd 的每种情况下,我无法计算出 RegEX
作为标准字符串解析很容易做到,但不幸的是,因为业务对象需要通过以下方式完成regex :-( 并通过 vb.net RegEX.matche,groups("Code1") fg 返回(我希望这是有道理的)
提前感谢您的任何帮助
最终得到了一些可以完成这项工作的 RegEx,有点混乱,但是 有效
(^(?<code1>[\w]*)$)|(^(?<code2>[\w]*):(?<code1>[\w]*)$)|(^(?<code3>[\w]*):(?<code2>[\w]*):(?<code1>[\w]*)$)|(^(?<code4>[\w]*):(?<code3>[\w]*):(?<code2>[\w]*):(?<code1>[\w]*)$)
一切都
Stuggling a little bit with the RegEx, I've got 4 codes in a string
CODE4:CODE3:CODE2:CODE1
each code is optional apart from CODE1
So I could have ab:bc:de:fg
or
bc::fg
of
ab:::fg
In each case of the above CODE1 = fg dnd for the dear life of me I can't work out the RegEX
Would be easy to do as a standard string parse, but unforunatly because of buisness objects in needs to be done via regex :-( and return via a vb.net RegEX.matche,groups("Code1") fg (I hope that makes sense)
Thanks in advance for any help
Ended up with a bit of RegEx that does the job, bit messy but it works
(^(?<code1>[\w]*)$)|(^(?<code2>[\w]*):(?<code1>[\w]*)$)|(^(?<code3>[\w]*):(?<code2>[\w]*):(?<code1>[\w]*)$)|(^(?<code4>[\w]*):(?<code3>[\w]*):(?<code2>[\w]*):(?<code1>[\w]*)$)
Ta all
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里不需要使用正则表达式。
我不知道您使用的是什么语言,但是将字符串拆分为“:”,您将得到一组代码。
如果您真的只是想验证字符串是否有效,那么
请匹配您的描述和您给出的几个示例。
There's no need to use a regular expression here.
I don't know what language you're using, but split the string on ':' and you'll have an array of codes.
If you really just want to validate whether a string is valid for this then
matches your description and the few examples you've given.
我不知道为什么你必须从右到左匹配代码。 只需使用正则表达式来分离字符串:
然后您就可以在 $4 中得到 CODE1,在 $3 中得到 CODE2,在 $2 中得到 CODE3,在 $1 中得到 CODE4。
I'm not sure why you have to match the codes right to left. Simply use a regular expression to pick apart the string:
and then you have CODE1 in $4, CODE2 in $3, CODE3 in $2, CODE4 in $1.
(CODE1)?:(CODE2)?:(CODE3)?:CODE4
可以工作 - 如果前导 : 不重要。 否则,如果不能有前导冒号,请枚举:(CODE1:(CODE2)?:(CODE3)?:|CODE2:(CODE3)?:|CODE3)?CODE4
没有什么特别的事实上,最右边的部分是强制性的,而最左边的部分则不是。
(CODE1)?:(CODE2)?:(CODE3)?:CODE4
would work - if the leading : don't matter. Otherwise, if you can't have leading colons, enumerate:(CODE1:(CODE2)?:(CODE3)?:|CODE2:(CODE3)?:|CODE3)?CODE4
There's nothing special about the fact that the right-most part is mandatory, and the left-most parts aren't.