使用正则表达式实时验证用户输入及扩展支持减号方案
实时验证11A11格式输入的实现方案
我已经将Wiktor提供的方案落地到目标需求场景中,实现了用户输入过程中实时验证内容匹配11A11格式的功能,具体代码如下:
Private Sub RegexFormatterExample(sender As Object, e As EventArgs) Dim txt As TextBox = sender Dim pattern As String = "" Select Case txt.Name Case "txt_example" pattern = "^\d{1,2}(?:(?<=^\d{2})[A-Z]\d{0,2})?$" Case Else pattern = "^\d{1,2}(?:(?<=^\d{2})[A-Z]\d{0,2})?$" End Select Dim strText As String = txt.Text While Not Regex.IsMatch(strText, pattern) AndAlso Not strText = "" strText = strText.Substring(0, strText.Length - 1) End While txt.Text = strText txt.Select(txt.Text.Length, 0) End Sub
我已经为指定的TextBox绑定了.TextChanged事件处理程序,目前这个方案已经完全满足需求中的格式限制要求,在此特别感谢Wiktor的指导!
补充说明
针对用户需要输入**单个减号(而非空字符串)**来表示未知值的场景,我对正则表达式进行了调整(具体规则可参考正则表达式演示)。虽然暂时不确定这是不是最优实现,但目前运行状态一切正常,能够覆盖目标场景的需求。
内容的提问来源于stack exchange,提问作者Oliver
相关产品推荐
相关产品推荐

