How to Regex.IsMatch at a specified offset in .NET?
- by romkyns
Suppose I want to match "abc" within the string s only if it occurs exactly at index n.
int n = 2;
Console.WriteLine(new Regex("abc").IsMatch("01abc", n)); // true
Console.WriteLine(new Regex("abc").IsMatch("0123abc", n)); // true (but want false)
Console.WriteLine(new Regex("^abc").IsMatch("01abc", n)); // false (but want true)
Seems that the only way to achieve this without using Substring on the input is something like this:
var match = new Regex("abc").Match("0123abc", n);
Console.WriteLine(match.Success && match.Index == n);
This isn't too bad, except that when there is no match at the starting offset then the entire input will be scanned unnecessarily, which is probably slower for most regexes than actually creating a substring prior to the match. (I didn't time it though).
Am I missing an obvious overload or setting that would restrict a match to the supplied offset only?