I’m trying to validate some user input for the country code of a phone number. The country code is optional, but when it contains a value it should be 1 to 4 digits. I wrote a regular expression and expected the regular expression to fail when passing "n"
in C#. It appeared to match, so I popped open the C# interactive console in Visual Studio 2022 (version 17.8.6). Indeed, the pattern was matching a newline character unexpectedly. My experiments below:
Microsoft (R) Visual C# Interactive Compiler version 4.8.0-7.23572.1 ()
Loading context from 'CSharpInteractive.rsp'.
Type "#help" for more information.
> using System.Text.RegularExpressions;
> Regex.IsMatch("n", "^[0-9]{0,4}$")
true
> Regex.IsMatch("n", "^[0-9]{0,4}$", RegexOptions.Multiline)
true
> Regex.IsMatch("n", "^[0-9]{0,4}$", RegexOptions.Singleline)
true
> Regex.IsMatch("n", "^[0-9]{0,4}$", RegexOptions.None)
true
> Regex.IsMatch("n", "^[0-9]{0,4}$", RegexOptions.IgnorePatternWhitespace)
true
> Regex.IsMatch("n", "^\d{0,4}$")
true
Screenshot of the C# interactive console:
Just out of curiosity, I opened the Google Chrome console and entered this JavaScript:
let pattern = /^d{0,4}$/
undefined
pattern.test("n")
false
pattern = /^[0-9]{0,4}$/
pattern.test("n")
false
Screenshot of Chrome:
This has definitely left me scratching my head.
Why does Regex.IsMatch
report that a newline matches (beginning of line); zero or more digits; (end of line) when given a string with a single newline – "n"
?
1