I am looking for a regex to do the following:
- Return the index of the first instance of a given character not inside double quotes (I can guarantee a matching closing double quote will always be present and the character to search for will never itself be a double quote)
- Allow starting from
int startIndexposition
Speed is one of my primary concerns here so the number of iterations should be as small as possible.
Examples (all examples set to look for !, but this might not always be the case):
!something- should return 0!should also return 0something!should return 9"something!"should fail"some!thing"!should return 12!"!"!should return 0""!should return 2""!""should return 2!somethingwithstartIndex == 2should fail!something!withstartIndex == 2should return 10 (despite starting at position 2, the index of the character on the given string is still 10)
Since this is for .NET the intention is to use Regex.Match().Index (unless a better alternative is provided).
I suggest good old
forloop instead of regular expressions; let's implement it as an extension method:And so, you can use it as if
IndexOfQuotedastrings method:Demo:
Outcome: