Regex to match all words except a given list

后端 未结 6 939
Happy的楠姐
Happy的楠姐 2020-12-08 21:15

I am trying to write a replacement regular expression to surround all words in quotes except the words AND, OR and NOT.

I have tried the following for the match par

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-08 22:06

    Call me crazy, but I'm not a fan of fighting regex; I limit my patterns to simple things I can understand, and often cheat for the rest - for example via a MatchEvaluator:

        string[] whitelist = new string[] { "and", "not", "or" };
        string input = "foo and bar or blop";
        string result = Regex.Replace(input, @"([a-z0-9]+)",
            delegate(Match match) {
                string word = match.Groups[1].Value;
                return Array.IndexOf(whitelist, word) >= 0
                    ? word : ("\"" + word + "\"");
            });
    

    (edited for more terse layout)

提交回复
热议问题