dotnet / dotnet/dotnet-api-docs
Regex examples should use "\z" not "$" for end-of-string
- Dominant language
- C#
- Stars
- 949
- Forks
- 1.7k
- Avg merge
- 3d 27m
- Merged PRs (30d)
- 49
Description
The documentation for `Regex.IsMatch` (in [Regex.xml](https://github.com/dotnet/dotnet-api-docs/blob/main/xml/System.Text.RegularExpressions/Regex.xml)) includes an example pattern `^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$`. It describes the trailing "$" as "End the match at the end of the line". This is not entirely accurate: [Anchors in Regular Expressions](https://docs.microsoft.com/en-us/dotnet/standard/base-types/anchors-in-regular-expressions) says that "The $ anchor specifies that the preceding pattern must occur at the end of the input string, or before \n at the end of the input string", and testing confirms this behavior. This means that the example pattern accepts part number `"1298-673-4192\n"`, which is a subtle validation bug.
Proposed fix: Use the anchor "\z" instead of "$".
This fix is relevant because Java, PCRE, and various other regex engines have "$" behave like dotnet's "\z". `Regex.IsMatch` should draw attention to the correct anchor, to help developers avoid validation bugs.
Contributor guide
Assessment
This issue has not been assessed yet.