使用正则表达式进行部分搜索?

时间:2012-10-18 20:00:41

标签: c# regex .net-4.0

如果我使用RegEx作为TextBox的掩码,并且掩码应允许格式000-XXXXXX,例如,它允许3个字母,短划线,则6个数字,我怎样才能让用户只需要输入掩码的前3个字符用于搜索,而不是因为它不满足完整的RegEx而无法输入它们的内容? / p>

1 个答案:

答案 0 :(得分:2)

您可以将正则表达式的某些部分设为可选:

^\d{3}(?:-\d{0,6})?$

<强>解释

^        # Start of string
\d{3}    # Match 3 digits
(?:      # Try to match... 
 -       #  a dash
 \d{0,6} #  followed by up to 6 digits
)?       # but make that part of the match optional
$        # End of string
相关问题