为什么顺序在这个 RegEx 中很重要并有交替? [英] Why order matters in this RegEx with alternation?

查看:26
本文介绍了为什么顺序在这个 RegEx 中很重要并有交替?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TextBox 控件的要求是接受以下作为有效输入:

Requirements for a TextBox control were to accept the following as valid inputs:

  1. 一个数字序列.
  2. 文字字符串房间数".
  3. 根本没有价值(留空).根本不指定值应该允许 RegularExpressionValidator 通过.

遵循 RegEx 产生了预期的结果(成功验证了 3 种类型的输入):

Following RegEx yielded the desired results (successfully validated the 3 types of inputs):

"Number of rooms|[0-9]*"

但是,当一位同事询问为什么在指定字符串房间数"时以下内容无法验证(要求 2)时,我无法给出解释:

However, I couldn't come up with an explanation when a colleague asked why the following fails to validate when the string 'Number of rooms' is specified (requirement #2):

"[0-9]*|Number of rooms"

关于为什么在这种情况下交替的顺序很重要的解释确实非常有见地.

An explanation as to why the ordering of alternation matters in this case would be very insightful indeed.

更新:

第二个正则表达式成功匹配控制台应用程序中的目标字符串房间数",如此处所示.但是,当输入为房间数"时,在 aspx 标记中使用相同的表达式不匹配.这是相关的 aspx 标记:

The second regex successfully matches the target string "Number of rooms" in console app as shown here. However, using the identical expression in aspx markup doesn't match when the input is "Number of rooms". Here's the relevant aspx markup:

<asp:TextBox runat="server" ID="textbox1" >
</asp:TextBox>

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" 
EnableClientScript="false" runat="server" ControlToValidate="textbox1" 
ValidationExpression="[0-9]*|Number of rooms" 
ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionValidator>

<asp:Button ID="Button1" runat="server" Text="Button" />

推荐答案

顺序很重要,因为这是 Regex 引擎将尝试匹配的顺序.

The order matters since that is the order which the Regex engine will try to match.

案例 1:房间数|[0-9]*

在这种情况下,正则表达式引擎将首先尝试匹配文本房间数".如果失败,将尝试匹配数字或不匹配.

In this case the regex engine will first try to match the text "Number of room". If this fails will then try to match numbers or nothing.

情况 2:[0-9]*|房间数:

在这种情况下,引擎将首先尝试匹配数字或不匹配.但是没有什么总是匹配的.在这种情况下,它永远不需要尝试房间数量"

In this case the engine will first try to match number or nothing. But nothing will always match. In this case it never needs to try "Number of rooms"

这有点像 ||C#中的运算符.一旦左侧匹配右侧将被忽略.

This is kind of like the || operator in C#. Once the left side matches the right side is ignored.

更新:回答你的第二个问题.它与 RegularExpressionValidator 的行为不同,因为它所做的不仅仅是检查匹配.

Update: To answer your second question. It behaves differently with the RegularExpressionValidator because that is doing more than just checking for a match.

// .....
Match m = Regex.Match(controlValue, ValidationExpression);
return(m.Success && m.Index == 0 && m.Length == controlValue.Length); 
// .....

它正在检查匹配并确保匹配的长度是整个字符串.这排除了部分或空匹配.

It is checking for a match as well as making sure the length of the match is the whole string. This rules out partial or empty matches.

这篇关于为什么顺序在这个 RegEx 中很重要并有交替?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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