The problem is when one tries to look for a pattern inside a string, with a start position. And one uses the caret to avoid looking for matches except at this position. Since this is a long string, one wants to avoid either taking a substring (which is O(N) ) or looking for matches except at the start.
For instance
static void Main(string[] args)
{
Regex r = new Regex("^foo");
string s = "afoo";
var result = r.Match(s, 1);
Console.WriteLine($"result {result.Success}");
}
This match should succeed, but it does not.
Otherwise, is there any efficient method for looking for matches in a string from particular position that is not O(N) ?
When I was in this situation, I found \G useful: https://docs.microsoft.com/dotnet/standard/base-types/anchors-in-regular-expressions#Contiguous
It only works if the position you wish to start from is always the end of the previous match.
@jnm2 Thank you, the trick worked. But it is counterintuitive.
Interesting behavioral question to consider when considering Span overloads. My assumption is that they would work like a substring is passed in
https://github.com/dotnet/corefx/issues/24145
Just hit this as well - it definitively is counter intuitive to behave like this though \G does work as a replacement to ^.
@danmosemsft - I assume because of backwards compatibility that the current Regex.Match(string text, int startat) won't change and if we want what seems like the intended behaviour (without switching to \G over ^), we would be best to use Span<char> once support for that is added?
@Turnerj probably, cc @stephentoub for thoughts since he's worked in this most recently.
Yeah, I wouldn't expect this to change for the string-based methods.