Carlos28 Carlos28 - 4 years ago 279
C# Question

WPF MaskedTextbox and "\" character

I'm using helper from this article to create

MaskedTextbox
and I have problem with
\
character, if my mask contains this character

b:Masking.Mask="^[0-9]{1,4}\_$"


I get

'MaskExpression' property was registered as read-only and cannot be modified without an authorization key.


in
XAML
file, but I can start application, after starting I get:

Additional information: analyzing "^[0-9]{1,4}\_$" - Unrecognized escape sequence \_.


At:

SetMaskExpression(textBox, new Regex(mask, RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace));


I have tried also using:

\\
\


Instead
\
but it give this same result. How can I fix this?

Answer Source

Note that a _ (underscore) is not considered a regex special metacharacter and should not be escaped.

b:Masking.Mask="^[0-9]{1,4}_$"

Note that only special regex metacharacters that have special meaning should be escaped.

See Character Escapes in the .NET Framework reference:

The characters included in the Character or sequence column (. $ ^ { [ ( | ) * + ? \ - WS) are special regular expression language elements. To match them in a regular expression, they must be escaped or included in a positive character group. For example, the regular expression \$\d+ or [$]\d+ matches "$1200".

Characters other than those listed in the Character or sequence column have no special meaning in regular expressions; they match themselves.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download