KatDevsGames
KatDevsGames

Reputation: 1156

Regex to match a string ending with a certain character but not beginning with another with intermediary whitespace

I am attempting to use the regex: (?<!:)[\s]+" to no effect.

What I want is to match a quote mark preceded by whitespace UNLESS the whitespace is preceded by a colon.

The above regex is useless however as it matches incorrectly. The regex above will match the string :__" (using _ to represent a space) because it just matches _". It starts matching at the second space, but it shouldn't match at all.

I'm looking for:

A " - MATCH
B " - MATCH
: " - NO MATCH
A:   " - NO MATCH
:    " - NO MATCH
:                           " - NO MATCH
:                A " - MATCH

The negative lookbehind doesn't help because it does match most of them.

Upvotes: 2

Views: 434

Answers (2)

jdweng
jdweng

Reputation: 34419

Try this

      const string FILENAME = @"\temp\test.txt";
        static void Main(string[] args)
        {
            string input = File.ReadAllText(FILENAME);
            string pattern = "^[^:]\\s+\"";

            MatchCollection matches = Regex.Matches(input, pattern, RegexOptions.Multiline);
        }​

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

One way to match the strings that you want is to require a character other than a space \s or colon : to be present in front of \s+:

(?<![:\s])\s+"

Including space \s in the list of negative look-behind ensures that a space cannot be counted as "not-a-colon" character for the purpose of matching a string.

Demo.

Upvotes: 3

Related Questions