1

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?

Community
  • 1
  • 1
Carlos28
  • 2,381
  • 3
  • 21
  • 36
  • Why escape `_`? Use `b:Masking.Mask="^[0-9]{1,4}_$"`. Or do you want to match a literal backslash? Then use `"^[0-9]{1,4}\\\\_$"` or `@"^[0-9]{1,4}\\_$"`. What is the valid input? – Wiktor Stribiżew Feb 06 '17 at 11:22
  • It's not clear what you are trying to achieve. Error happens because your regex is invalid. If you want to include "\" character in regex - escape it: "^[0-9]{1,4}\\_$" – Evk Feb 06 '17 at 11:27
  • I thought that I need to use \ before _, my bad – Carlos28 Feb 06 '17 at 11:47
  • Excuse me, could you please provide a sample string that you consider valid? Is `1_` valid or `1\_` string valid? – Wiktor Stribiżew Feb 06 '17 at 12:01

1 Answers1

2

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563