dotnet / dotnet/dotnet-api-docs

Regex examples should use "\z" not "$" for end-of-string

Open
#5,422 2 comments 0 reactions 0 assignees View on GitHub
:books: documentation area-System.Text.RegularExpressions Pri3
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

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.