C# Regex.Replace() swallowing part of original string

C# Regex.Replace() swallowing part of original string

Looking at the documentation, since youve specified RegexOptions.Multiline, the ^ anchor matches the beginning of a line, not the beginning of the string.

As a result, your pattern matches:

FROM root
ORDER BY root[UtcTimestamp] DESC

You then replace that with the value of the first capture, which is:

{n}
ORDER BY root[UtcTimestamp] DESC

which gives the result:

SELECT *

ORDER BY root[UtcTimestamp] DESC

Its not clear what output you were expecting. If you just want to remove the entire ORDER BY clause, then add a group to capture the prefix:

var endsWithOrderBy = new Regex(^(.+)(\s+ORDER\s+BY\s+.+)$, ...);

You can use this:

s*n?s*(ORDERs+BYs+.*)$

If you use an anchor for the start of the line (^) you cannot match when the ORDER BY is not preceded by a line break, i.e. SELECT * FROM root ORDER BY root[UtcTimestamp] DESC.

Check here: https://regex101.com/r/gQ2rQ1/2

Im using the g modifier so you can test multiple sentences, but you wont need it.

C# Regex.Replace() swallowing part of original string

Leave a Reply

Your email address will not be published. Required fields are marked *