Repository navigation
Description
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
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 thatAnyNewLine = 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
svick commentedon Mar 24, 2018
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 likeAnyNewLine.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):
EnvironmentNewLineAnyNewLinejzabroski commentedon Mar 24, 2018
jzabroski commentedon Mar 24, 2018
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.
[-]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)[/+]jzabroski commentedon Mar 26, 2018
@jnm2 @svick I updated the original description. Please give feedback.
ViktorHofer commentedon Mar 27, 2018
I like the idea and its cross-platform benefit.
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.
svick commentedon Mar 27, 2018
@ViktorHofer
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
I don't understand this regex, as far as I can tell, it wouldn't match
\r\n, and so\r\nwould be reported as two line breaks.jzabroski commentedon Mar 27, 2018
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.
ViktorHofer commentedon May 24, 2018
potential hackathon candidate if we review the API addition in time.
cc @karelz
terrajobst commentedon May 29, 2018
Video
Looks good. A few comments:
#if DBGin code)AcceptAllLineEndings?svick commentedon May 29, 2018
@terrajobst
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:
For me, running it on .Net Core 2.1 RTM on Windows 10 prints:
While if this was "working well", I would expect to get just the three characters of
"foo"as the match, not"foo\r".jzabroski commentedon May 29, 2018
@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.
jzabroski commentedon May 30, 2018
@terrajobst
I'll update the original post to modify the enum options to be 0x0400 (1024)
Mpdreamz commentedon Jun 2, 2018
Taking a stab at this for the Hackaton
41 remaining items
danmoseley commentedon Jun 18, 2023
@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.)
danmoseley commentedon Aug 13, 2023
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
stephentoub commentedon Aug 13, 2023
You mean someone else would add it for the other engines?
danmoseley commentedon Aug 13, 2023
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
danmoseley commentedon Aug 13, 2023
What are your thoughts, would it be acceptable to only support for static patterns (generator)
stephentoub commentedon Aug 13, 2023
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.
gregli-msft commentedon Mar 6, 2025
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\nfor 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:
Dot divisible: Dan brought up that
\r\nshould 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\nas 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,
/%.%/sshould match%\r\n%. Am I misunderstanding?For example, both fail as written here, but succeed with
\ror\nalone.console.log( "%\r\n%".match( /%.%/s ) )with JSFiddle.=REGEXTEST("%" & CHAR(13) & CHAR(10) & "%", "(?s)%.%" ).Caret and Dollar indivisible: I do think it makes sense for
\r\nto be treated as one for these anchors. The test case that swayed me is/(%|)$/mgwith%\r\n%. On JavaScript, that will result in 3 matches: two for "a" and a third for the empty match after the\rbut before the\n(see the JSFiddle).PCRE2 only returns the two
aresults 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
\Aor\zsupport.Newline characters: This thread started out specifically about adding
\r. TR18#1.6 calls out 7 newline characters, not including the\r\ncombination. Dan's lowering supported 5 characters, dropping\vand\f(somewhat dated?). For reference, PCRE2 has two relevant modes,ANYCRLFwith any combination of\rand\nwhich is what Excel is using, andANYwhich 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
\ras 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.
danmoseley commentedon Feb 21, 2026
Updating my earlier tables with one correction: the
.withSingleLine | AnyNewLinerow. Making.match either 1 or 2 characters (\r\nas 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) whenSingleLineis set, regardless ofAnyNewLine.Anchor lowering
^lowered to (no capture)$lowered to (no capture)\Zlowered to (no capture)\A(?=\z|\n\z)$with neither)AnyNewLine\A(?=\r\n\z|[\r\u0085\u2028\u2029]?\z)|(?<!\r)(?=\n\z)$withAnyNewLine)Multiline(?<=\A|\n)(?=\z|\n)$with neither)Multiline | AnyNewLine(?<=\A|\r\n|[\n\u0085\u2028\u2029])|(?<=\r)(?!\n)(?=\r\n|[\r\u0085\u2028\u2029]|\z)|(?<!\r)(?=\n)$withAnyNewLine)Dot lowering
.lowered to (it captures)[^\n]AnyNewLine[^\n\r\u0085\u2028\u2029]SingleLine.SingleLine | AnyNewLine.\Rlowering (if added)\Rlowered to (it captures)\r\n|(?!\r\n)[\n\r\u0085\u2028\u2029]Only the
AnyNewLinerows represent new lowering; the other rows describe existing behavior expressed as equivalent patterns for comparison.danmoseley commentedon Mar 3, 2026
@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.
Add RegexOptions.AnyNewLine via parser lowering (dotnet#124701)