正则表达式排除特定字符串

问题描述 投票:0回答:2

我需要一个.NET正则表达式匹配来自"[@foo]""applicant_data/contact_number[@foo]" w / c我已经可以使用模式"\[@(.*?)\]"

但是我想做一个例外,以便"applicant_data/contact_number[@foo=2]"与模式不匹配。所以问题是正则表达式应该是什么,以便它将获得任何有效的字母数字([@ bar],[@ theVar],[@ zoo $ 6])但不是[@ bar = 1],[@ theVar = 3] ?

c# .net regex
2个回答
1
投票

你可以试试这个:

\[@[\w-]+(?!=)\]

说明:

"\[" &       ' Match the character “[” literally
"@" &        ' Match the character “@” literally
"[\w-]" &    ' Match a single character present in the list below
                ' A “word character” (Unicode; any letter or ideograph, digit, connector punctuation)
                ' The literal character “-”
   "+" &        ' Between one and unlimited times, as many times as possible, giving back as needed (greedy)
"(?!" &      ' Assert that it is impossible to match the regex below starting at this position (negative lookahead)
   "=" &        ' Match the character “=” literally
")" &
"\]"         ' Match the character “]” literally

希望这可以帮助!


1
投票

试试这个正则表达式:

\[@(?![^\]]*?=).*?\]

Click for Demo

说明:

  • \[@ - 字面上匹配[@
  • (?![^\]]*?=) - 负向前瞻以确保在下一个=之前]不在任何地方
  • .*? - 匹配除换行符之外的任何字符的0+次出现
  • \] - 字面上匹配]
© www.soinside.com 2019 - 2024. All rights reserved.