正则表达式返回条件组
我花了很多时间找出一个简单的正则表达式来返回一个组(仅第一组)。
所以字符串可以是 - “无需购买”或“需要购买价值 50.00 美元的杂货”。
我正在尝试编写一个正则表达式,它可以根据给定的字符串解析“No”或“50”。
这是我写的。
(?:(No) monthly maintenance|Purchase of \$([\d\.]+ worth groceries)
这工作正常,但我希望我的输出仅作为第一组/组 1。
I spent lot time figuring out a simple regex to return a group (only 1st group).
So the string can be -
"No purchase required" or "Purchase of $50.00 worth groceries is required."
I am trying to write a regex which can parse "No" or "50" based on the given string.
This is what I have written.
(?:(No) monthly maintenance|Purchase of \$([\d\.]+ worth groceries)
This works fine but I want my output as 1st group/group 1 only.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不直接使用
/(?:无需每月维护|购买价值 $([0-9.]+) 的杂货)/
。如果不是这些格式之一,则匹配将失败,并且组 1 匹配“无每月维护”案例的
''
或其他案例的编号。如果您确实需要捕获字符串
No
或数字,您可能需要变得更复杂一点,并执行以下操作:Why not just use
/(?:No monthly maintenance|Purchase of $([0-9.]+) worth groceries)/
.The match will fail if it's not in one of those formats, and Group 1 matches
''
for the "No monthly maintenance" case, or the number for other case.If you really need to capture the string
No
or the number, you might need to get a little more complicated and do something like:大多数语言都会按顺序计算匹配组,无论它们是否属于非捕获组 (
(?:...|...)
),因此将有趣的部分强制放入第一个捕获中团体可能会带来更多麻烦,而不是其价值。根据您使用的语言,您可能想要尝试使用两个不同的预编译正则表达式并返回第一个匹配的匹配组,这样您就可以轻松地将有趣的部分放入第一组中。
Most languages count the matching groups in order, regardless of whether they are in a non-capturing group (
(?:...|...)
), so forcing the interesting part into the first capturing group might be more trouble than it's worth.Depending on what language you are using you might want to try using two different precompiled regular expressions and return the matching group of the first match, that way you can easily fit the interesting part into the first group.
我不确定您是否可以在第 1 组中获得结果,但是您可以让两个结果出现在同一个命名组中。下面是 PowerShell 中的一个示例:
其结果如下:
但并非所有语言都支持命名组。由于 PowerShell 在 .NET Framework 上运行,因此这适用于任何 .NET 语言。
I'm not sure you can get the result in group number 1, but you can get both results to appear in the same named group. Here's an example in PowerShell:
Which results in the following:
Not all languages support named groups though. Since PowerShell runs on the .NET Framework, this will work for any .NET language.