You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用正则表达式实时验证用户输入及扩展支持减号方案

实时验证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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 22:28:16