简体   繁体   中英

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.

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.

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);
        }​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM