Skip to content

Regex Match, Split and Matches should support RegexOptions.AnyNewLine as (?=\r\z|\n\z|\r\n\z|\z) #25598

Closed

Description

@jzabroski

From MSDN:

By default, $ matches only the end of the input string. If you specify the RegexOptions.Multiline option, it matches either the newline character (\n) or the end of the input string. It does not, however, match the carriage return/line feed character combination. To successfully match them, use the subexpression \r?$ instead of just $.

This is by far one of the biggest gotchas with using .NET Regex class.

I suggest adding a RegexOptions.AnyNewLine which treats $ as matching both Windows' Environment.NewLine and UNIX' Environment.NewLine, regardless of the Environment running corefx.

Portability concerns
According to Wikipedia, there are a ton of different operating systems, all with different line ending settings. The current implementation hardcodes Unix line-ending style. RegexOptions.AnyNewLine, defined as (?=[\r\n]|\z), would add support for Windows line-ending style.

The advise written in the current docs is actually not portable on Unix, which is becoming a more popular option. As it is suggested, \r?$ will capture one or two lines on Unix, and one on Windows. If you try running Windows assemblies with this hack on Linux, you will change the semantics of programs.

Backward compatibility concerns
Fully backward compatible: This RegexOptions enum extension would not be a default, and so it would not break any clients with reasonably written code. The only existing code that might display different behavior would be reflection code that sets every option on RegexOptions enum variable. I really can't envision anyone doing this on purpose.

Here is Petr Onderka (@svick)'s summary:

OS Line-ending style Current Environment.NewLine AnyNewLine
Windows Windows ✗ ✓ ✓
Windows Unix ✓ ✗ ✓
Unix Windows ✗ ✗ ✓
Unix Unix ✓ ✓ ✓

Api Proposal

edit by @ViktorHofer

namespace System.Text.RegularExpressions
{
    [Flags]
    public enum RegexOptions
    {
        None                    = 0x0000,
        IgnoreCase              = 0x0001, // "i"
        Multiline               = 0x0002, // "m"
        ExplicitCapture         = 0x0004, // "n"
        Compiled                = 0x0008, // "c"
        Singleline              = 0x0010, // "s"
        IgnorePatternWhitespace = 0x0020, // "x"
        RightToLeft             = 0x0040, // "r"

#if DEBUG
        Debug                   = 0x0080, // "d"
#endif

        ECMAScript              = 0x0100, // "e"
        CultureInvariant        = 0x0200,
+       AnyNewLine              = 0x0400 // Treat "$" as (?=[\r\n]|\z)
    }
}

API Review Notes

Video

Looks good. A few comments:

  • We cannot use the proposed value of 128 because it's already taken (see #if DBG in code) Spec updated so that AnyNewLine = 0x400 (1024).
  • The table looks wrong (Windows on Windows on the Current should work IMHO) The table is correct. The fact this trips up experts just speaks to why this is a profound GOTCHA in the Core SDK.
  • May be AcceptAllLineEndings? Some hallway testing I've done indicates AnyNewLine is a good name. Plus, (argument after the final name was chosen) this enumeration will be transliterated into a checkbox on Regular Expression Visualization tools like Regex Hero, so it is preferable to have a concise explanation for the feature to avoid excessive screen space.

PR Review Notes

After work had started on the approved proposal, @danmosemsft asked if the scope of this feature should be changed to also adjust the meaning \Z anchor. @jzabroski suggested writing how the end user documentation will look after this change, as good docs will determine if it is a function step improvement in usability and reducing gotchas.

Also, during the PR, it seems @shishirchawla also proposed AnyEndZ as a way to use AnyNewLine as an "Anchor Modifier", which will alter the meaning of '\Z' anchor in addition to altering the meaning of '$' anchor. The intent of this improvement appears to be to remove all platform-specific language from the Anchors documentation, which seems like a great improvement.

AnyNewLine as Anchor Modifier to \Z and $ Anchors

flags $ is treated as $ documentation \Z is treated as \Z documentation
neither (?=\n\z|\z) The match must occur at the end of the string or before \n at the end of the string. (Same as $ with this option.) (Same as $ with this option.)
RegexOptions.Multiline (?=\n|\n\z|\z) The match must occur at the end of the string or before \n anywhere in the string. (?=\n\z|\z) The match must occur at the end of the string or before \n at the end of the string.
RegexOptions.Multiline | RegexOptions.AnyNewLine (?=\r\n|\r|\n|\r\n\z|\r\z|\n\z|\z) The match must occur at the end of the string or before \r\n, \n or \r anywhere in the string. (?=\r\n\z|\r\z|\n\z|\z) The match must occur at the end of the string or before \r\n, \n or \r at the end of the string.
RegexOptions.AnyNewLine (?=\r\n\z|\r\z|\n\z|\z) The match must occur at the end of the string or before \r\n, \n or \r at the end of the string. (Same as $ with this option.) (Same as $ with this option.)

Activity

  1. svick commented on Mar 24, 2018

    @svick
    Member

    I don't like that this would depend on Environment.NewLine. Transferring files between different OSes is common, so I think there is a good chance you will need to process files with different line endings than those that are native to your OS. Instead, I think a setting that would match any line ending (independent of the current OS) would be better. It could be called something like AnyNewLine.

    Here is a table comparing the options (✓ means processing files with the given line-ending style works well on the given OS, ✗ means it does not):

    OS Line-ending style Current EnvironmentNewLine AnyNewLine
    Windows Windows ✗ ✓ ✓
    Windows Unix ✓ ✗ ✓
    Unix Windows ✗ ✗ ✓
    Unix Unix ✓ ✓ ✓
  2. jzabroski commented on Mar 24, 2018

    @jzabroski
    ContributorAuthor
  3. jzabroski commented on Mar 24, 2018

    @jzabroski
    ContributorAuthor

    Actually, I see now that in my original description my description of the behavior is inconsistent. Thank you for that wonderful table. I will update the first post with it.

  4. changed the title [-]Regex Match, Split and Matches should support RegexOptions.EnvironmentNewLine as (?=[\r\n]|\z)[/-] [+]Regex Match, Split and Matches should support RegexOptions.AnyNewLine as (?=[\r\n]|\z)[/+] on Mar 26, 2018
  5. jzabroski commented on Mar 26, 2018

    @jzabroski
    ContributorAuthor

    @jnm2 @svick I updated the original description. Please give feedback.

  6. ViktorHofer commented on Mar 27, 2018

    @ViktorHofer
    Member

    I like the idea and its cross-platform benefit.

    I think a setting that would match any line ending

    How is any line ending defined? The name suggests that it can handle any line ending, are there more than Unix and Windows line ending chars? We could probably refine the name.

  7. svick commented on Mar 27, 2018

    @svick
    Member

    @ViktorHofer

    How is any line ending defined?

    According to Wikipedia's summary of the Unicode standard, there are 8 character sequences that form a line break (7 single characters, including CR and LF, and the sequence CR+LF).

    Though I think those other characters are not widely used, so supporting only either LF and CR+LF (Unix and Windows) or CR, LF and CR+LF (old Mac, Unix and Windows) would be fine, especially if it lead to better performance than fully supporting the Unicode definition of line break.

    @jzabroski

    (?=[\r\n]|\z)

    I don't understand this regex, as far as I can tell, it wouldn't match \r\n, and so \r\n would be reported as two line breaks.

  8. jzabroski commented on Mar 27, 2018

    @jzabroski
    ContributorAuthor

    I'll write some test cases with XUnit and use that as a specification. We can then tweak the test cases to come up with a final specification/acceptance criteria. Fare could also be used to confirm.

  9. ViktorHofer commented on May 24, 2018

    @ViktorHofer
    Member

    potential hackathon candidate if we review the API addition in time.

    cc @karelz

  10. terrajobst commented on May 29, 2018

    @terrajobst
    Contributor

    Video

    Looks good. A few comments:

    • We cannot use the proposed value of 128 because it's already taken (see #if DBG in code)
    • The table looks wrong (Windows on Windows on the Current should work IMHO)
    • May be AcceptAllLineEndings?
  11. svick commented on May 29, 2018

    @svick
    Member

    @terrajobst

    The table looks wrong (Windows on Windows on the Current should work IMHO)

    I don't think the table is wrong, see the documentation linked in the top post, where it says that you should use \r?$ to match Windows-style line endings in multiline mode.

    You can also try running code like the following:

    var match = Regex.Match("foo\r\nbar", ".*$", RegexOptions.Multiline);
    
    foreach (char c in match.Value)
        Console.WriteLine($"{c} (0x{(int)c:X2})");

    For me, running it on .Net Core 2.1 RTM on Windows 10 prints:

    f (0x66)
    o (0x6F)
    o (0x6F)
     (0x0D)
    

    While if this was "working well", I would expect to get just the three characters of "foo" as the match, not "foo\r".

  12. jzabroski commented on May 29, 2018

    @jzabroski
    ContributorAuthor

    @terrajobst I agree with @svick . Intuitively, all his table is saying is that neither $ nor Environment.NewLine is fully portable solution for the two ubiquitous platforms. AnyNewLine therefore proposes to fill that gap.

  13. jzabroski commented on May 30, 2018

    @jzabroski
    ContributorAuthor

    @terrajobst

    I'll update the original post to modify the enum options to be 0x0400 (1024)

  14. Mpdreamz commented on Jun 2, 2018

    @Mpdreamz
    Contributor

    Taking a stab at this for the Hackaton

  15. 41 remaining items

  16. danmoseley commented on Jun 18, 2023

    @danmoseley
    Contributor

    @stephentoub I hacked up what lowering might look like -- see https://github.com/dotnet/runtime/compare/main...danmoseley:runtime:anynewline?expand=1#diff-548465bb4dbdd05024f0676c944e3c2b89677c48257bf28dfb0afccde31ded0aR19

    I wrapped the pattern in an iterator with the idea that it could show "real" locations in the pattern in error messages, but not sure whether it's worth that abstraction.

    Do you think this is a worthwhile direction?

    Edit: The approach makes those handful of tests pass. I'd need to do more tests/inspection to see whether there's other positional state that would need correction on inserting into the pattern like this, and update that too.

    I suspect perf with this lowering approach may be more of a worry than the parser. Once the flag exists, folks may update existing patterns to use it, which may then be a perf trap if they are "hot". Possibly adding \R would be less of a problem in this respect as it would require modifying the pattern, so less "easy", and by putting \R in a non capturing group or an assertion as appropriate you can achieve some of the same things as AnyNewLine albeit potentially in a clumsy way (but a standard way).

    So a possible approach might be to implement \R for .NET 8 then at a future point add AnyNewLine but properly, as it's own node type that the engines accommodate.

    (In this model \R would match any new line out of the gate, but that's the same as PCRE: by default in PCRE, . $ \Z recognize only \n but \R recognizes all newline flavors.)

  17. self-assigned this
    on Aug 13, 2023
  18. removed
    help wanted
    on Aug 13, 2023
  19. danmoseley commented on Aug 13, 2023

    @danmoseley
    Contributor

    I didn't like the parser approach -- it's clumsy and will run slow.
    I'm working on supporting this properly, but in the generator only -- that way we can do it efficiently plus avoid adding any runtime cost for the regular case.

    working in https://github.com/dotnet/runtime/compare/main...danmoseley:anynewline2?expand=1

  20. stephentoub commented on Aug 13, 2023

    @stephentoub
    Member

    I'm working on supporting this properly, but in the generator only

    You mean someone else would add it for the other engines?

  21. danmoseley commented on Aug 13, 2023

    @danmoseley
    Contributor

    Potentially, in future, with care to avoid impacting perf in existing cases. As AnyNewLine would be new, I think it's OK if only the new engine supports it (meaning it will only work for static patterns) initially.

    Just checking for more than \n is easy, the complexity is dealing with \r\n atomically

  22. danmoseley commented on Aug 13, 2023

    @danmoseley
    Contributor

    What are your thoughts, would it be acceptable to only support for static patterns (generator)

  23. stephentoub commented on Aug 13, 2023

    @stephentoub
    Member

    I think it's OK if only the new engine supports it (meaning it will only work for static patterns)

    I'm not a fan of that. At a minimum, when we support it, it should be in all but the NonBacktracking engine, but ideally all of them. There are currently zero differences in supported functionality between the interpreter, compiler, and source generator; I'm not excited to add any. Plus, there are cases where the source generator will fall back to the other engines, eg case-insensitive back references, so whether this new option would work would be very confusing.

  24. gregli-msft commented on Mar 6, 2025

    @gregli-msft

    Reviving an old thread, I ran across this work in adding regular expressions to Power Fx. We run on top of .NET and JavaScript and potentially other platforms in the future, so I'm trying to carve out a regular expression language that can either be lowered/transpiled and/or limited in expressiveness for consistency. Consistency with Excel's use of PCRE2 is important too. We've been successfully using XRegExp for many years in Power Apps so we are comfortable with the lowering approach. We can also be pretty opinionated about what we support, for example we are "no capture" by default and named and numbered captures can't be used together, partially because .NET and JavaScript treat mixing them differently, thus we effectively guide toward the better named captures.

    One area of inconsistency that we need to resolve is newline behavior, the subject of this issue. Power Apps already uses \r\n for newlines so I need that combination to work. I'm in the process of integrating the lowering formulas that @danmoseley posted earlier (thank you!) and they are working well.

    I have a few points/questions:

    1. Dot divisible: Dan brought up that \r\n should be indivisible and provided a lowering formula for . to make that work. I know that TR18#1.6 states "(CRLF) should match as if it were a single character" (their emphasis on "should") and they go on to say that it isn't required for conformance. In my research, I have been unable to find any regular expression engine that supports \r\n as a newline combination that does this. For me, it is odd that . could match anything but one character, that seems like a fundamental assumption.

      Practically, if I understand the requirement, /%.%/s should match %\r\n%. Am I misunderstanding?

      For example, both fail as written here, but succeed with \r or \n alone.

      • JavaScript: console.log( "%\r\n%".match( /%.%/s ) ) with JSFiddle.
      • Excel, using PCRE2: =REGEXTEST("%" & CHAR(13) & CHAR(10) & "%", "(?s)%.%" ).
    2. Caret and Dollar indivisible: I do think it makes sense for \r\n to be treated as one for these anchors. The test case that swayed me is /(%|)$/mg with %\r\n%. On JavaScript, that will result in 3 matches: two for "a" and a third for the empty match after the \r but before the \n (see the JSFiddle).

      PCRE2 only returns the two a results which seems correct, in Excel =REGEXEXTRACT( "%" & CHAR(13) & CHAR(10) & "%", "(?m)^(%|)", 1 ).

      No question here, I assume this is still the direction you all are headed, and what I plan to do with Power Fx. I just need to figure out how to do it in JavaScript without \A or \z support.

    3. Newline characters: This thread started out specifically about adding \r. TR18#1.6 calls out 7 newline characters, not including the \r\n combination. Dan's lowering supported 5 characters, dropping \v and \f (somewhat dated?). For reference, PCRE2 has two relevant modes, ANYCRLF with any combination of \r and \n which is what Excel is using, and ANY which supports all 7 Unicode newline characters. JavaScript supports 4 , the 5 Dan selected minus \x85.

      It may be impossible to tell what .NET will do until it is done. Still, we have to make a choice for Power Fx soon. I can see the simplicity of just adding \r as that is what is really needed, I can see Dan's compromise, and I can see respecting the full Unicode set. If we pursue lowering for .NET, which would be engaged only when this new option is selected, I don't know that additional characters are that much more expensive. If it is hand coded in a dozen or so places, and it impacts all users with or without the option selected, I can see going small.

      Any thoughts or guidance on which way this may go?

    Thanks for all the help! I'd love to see this work continue, but like all of you I am short on spare time. I'm happy to help however I can when this initiative does get rolling again.

  25. danmoseley commented on Feb 21, 2026

    @danmoseley
    Contributor

    Updating my earlier tables with one correction: the . with SingleLine | AnyNewLine row. Making . match either 1 or 2 characters (\r\n as a unit) would break the fundamental invariant that . always matches exactly one character — e.g., .{3} could match 4–6 chars. This diverges from TR18 §1.6 (which scopes newline-aware . to non-single-line mode only) and from PCRE, Java, and Perl. The fix is to leave . as . (match any single char) when SingleLine is set, regardless of AnyNewLine.

    Anchor lowering

    flags ^ lowered to (no capture) $ lowered to (no capture) \Z lowered to (no capture)
    neither \A (?=\z|\n\z) (Same as $ with neither)
    AnyNewLine \A (?=\r\n\z|[\r\u0085\u2028\u2029]?\z)|(?<!\r)(?=\n\z) (Same as $ with AnyNewLine)
    Multiline (?<=\A|\n) (?=\z|\n) (Same as $ with neither)
    Multiline | AnyNewLine (?<=\A|\r\n|[\n\u0085\u2028\u2029])|(?<=\r)(?!\n) (?=\r\n|[\r\u0085\u2028\u2029]|\z)|(?<!\r)(?=\n) (Same as $ with AnyNewLine)

    Dot lowering

    flags . lowered to (it captures)
    neither [^\n]
    AnyNewLine [^\n\r\u0085\u2028\u2029]
    SingleLine .
    SingleLine | AnyNewLine .

    \R lowering (if added)

    flags \R lowered to (it captures)
    any \r\n|(?!\r\n)[\n\r\u0085\u2028\u2029]

    Only the AnyNewLine rows represent new lowering; the other rows describe existing behavior expressed as equivalent patterns for comparison.

  26. added
    in-pr
    on Feb 21, 2026
  27. danmoseley commented on Mar 3, 2026

    @danmoseley
    Contributor

    @gregli-msft I only just saw your comment! I put up a PR for all this #124701 (which thanks to AI slightly improves the lowering). In particular I had no reason for omitting VT and FF so I'm glad you pointed that out.

  28. locked and limited conversation to collaborators on Apr 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-approvedarea-System.Text.RegularExpressionsin-pr

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions