繁体   English   中英

.NET正则表达“不是这个字符串”

[英].NET Regex for “not this string”

我是一个正则表达式的新手,需要一个表达式:

匹配“an”和“AN”但不匹配“和”或“AND”并匹配此谓词中的“o”和“O”但不匹配“or”或“OR”:

1和(2or3)AND(4OR5)的(6o7)AN(8O9)

基本上我无法弄清楚如何转换表达式:

var myRegEx = Regex("[0-9 ()]|AND|OR")

进入一个“除了”之外,不区分大小写的表达。

无法使用正则表达式单词边界功能,因为谓词不需要包含空格。

(已经提供了两个答案后添加):我还需要知道匹配的索引,这就是为什么我假设我需要使用Regex.Match()方法。

谢谢!

这是我最终得到的:

  private bool mValidateCharacters()
  {
     const string legalsPattern = @"[\d ()]|AND|OR";
     const string splitPattern = "(" + legalsPattern + ")";
     int position = 0;
     string[] tokens = Regex.Split(txtTemplate.Text, splitPattern, RegexOptions.IgnoreCase);

     // Array contains every legal operator/symbol found in the entry field
     // and every substring preceeding, surrounded by, or following those operators/symbols
     foreach (string token in tokens)
     {
        if (string.IsNullOrEmpty(token))
        {
           continue;
        }

        // Determine if the token is a legal operator/symbol or a syntax error
        Match match = Regex.Match(token, legalsPattern, RegexOptions.IgnoreCase);

        if (string.IsNullOrEmpty(match.ToString()))
        {
           const string reminder =
              "Please use only the following in the template:" +
              "\n\tRow numbers from the terms table" +
              "\n\tSpaces" +
              "\n\tThese characters: ( )" +
              "\n\tThese words: AND OR";
           UserMsg.Tell("Illegal template entry '" + token + "'at position: " + position + "\n\n" + reminder, UserMsg.EMsgType.Error);
           txtTemplate.Focus();
           txtTemplate.Select(position, token.Length);
           return false;
        }

        position += token.Length;
     }

     return true;
  }

Randal Schwartz的规则:当你知道你想要保留什么时,在Regex.Match使用捕获,当你知道要丢弃什么时使用Regex.Split

你写道你想要“除了之外的一切”,所以

var input = "1and(2or3)AND(4OR5)an(6o7)AN(8O9)";
foreach (var s in Regex.Split(input, @"[\d()]|AND|OR", RegexOptions.IgnoreCase))
  if (s.Length > 0)
    Console.WriteLine("[{0}]", s);

输出:

[an]
[o]
[AN]
[O]

要获取偏移量,请通过将正则表达式括在括号中来保存分隔符:

var input = "1and(2or3)AND(4OR5)an(6o7)AN(8O9)";
string pattern = @"([\d()]|AND|OR)";
int offset = 0;
foreach (var s in Regex.Split(input, pattern, RegexOptions.IgnoreCase)) {
  if (s.ToLower() == "an" || s.ToLower() == "o")
    Console.WriteLine("Found [{0}] at offset {1}", s, offset);
  offset += s.Length;
}

输出:

Found [an] at offset 19
Found [o] at offset 23
Found [AN] at offset 26
Found [O] at offset 30

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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