I want to find out whether a Regex matches at a specific location of a string.
Example:
Regex r = new Regex("d");
string s = "abcdefg";
I want the match function to find a match only if it is at the exact given location so that using the example above, matching at the locations 1, 3, and 5 should give no match, match, and no match, respectively. Unfortunately the C# Regex.Match method gives:
r.Match(s, 1); // => match ("d")
r.Match(s, 3); // => match ("d")
r.Match(s, 5); // => no match
I understand this is because the Regex.Match method searches forward for the first match, but how do I prevent this behavior without having to make substrings?
Add \G to the beginning of your regex:
Regex r = new Regex(@"\Gd");
string s = "abcdefg";
Console.WriteLine(r.Match(s, 1).Success); // False
Console.WriteLine(r.Match(s, 3).Success); // True
Console.WriteLine(r.Match(s, 5).Success); // False
\G anchors the match to the position where the previous match ended, or to the beginning of the string if there was no previous match. With the second argument to Match, you're effectively telling it there was a previous match, which ended at that location.
Use substring and the start-of-string anchor ^:
Regex r = new Regex("^d"); // Use the start of string anchor
string s = "abcdefg";
r.IsMatch(s.Substring(3)); // Match at exactly fourth character (0-based index 3)
Alternatively, to avoid copying the string in memory, use quantified .:
Regex r = new Regex("^.{3}d");
r.IsMatch("abcdefg");
The pattern ^.{3}d says
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With