Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find a Regex match at a specific location of the string in C#?

Tags:

c#

.net

regex

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?

like image 941
Matt Avatar asked Nov 15 '25 21:11

Matt


2 Answers

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.

like image 76
Alan Moore Avatar answered Nov 17 '25 11:11

Alan Moore


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

  • Start at the beginning of the string
  • Match exactly three characters of anything
  • Then match the letter 'd'
like image 36
Joshua Honig Avatar answered Nov 17 '25 10:11

Joshua Honig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!