[英]Regular Expression for Not Matching Exact Words
我希望我的reg ex接受集合中的字符[a-zA-Z0-9。\\?!%,],除了確切的單詞“not set”之外也不接受。
成功匹配的示例:
category1
myCategory
Hello World!!!
notset
不成功匹配的示例:
{empty string}
not set
Not Set
NOT SET
<script>
我正在使用.NET框架。
謝謝!
很明顯,您可以通過代碼測試“未設置”。 如果它必須是正則表達式,您可以使用否定前瞻 :
^(?!not set$)[a-zA-Z0-9.?!%, ]+$
AC#代碼示例如下:
Match m = Regex.Match(s, @"^(?!not set$)[a-zA-Z0-9.?!%, ]+$", RegexOptions.IgnoreCase);
if (m.Success)
{
// all is well
}
如果您希望匹配不區分大小寫(即“未設置”無效,但“未設置”有效),請使用:
Match m = Regex.Match(s, @"^(?!Not Set$)[a-zA-Z0-9.?!%, ]+$");
這可能有用^(?i:(?!not set)[a-z0-9.\\\\?!%, ])+$
(未經測試)
編輯
Didn't work for me. – Bob 4 hours ago
@Bob - 這是你的樣品。
成功匹配的示例:
category1
myCategory
Hello World!!!
notset
不成功匹配的示例:
{empty string}
not set
Not Set
NOT SET
<script>
什么不起作用?
@samples = (
'category1',
'myCategory',
'Hello World!!!',
'notset',
'',
'not set',
'Not Set',
'NOT SET',
'<script>'
);
for (@samples) {
print "'$_'";
if (/^(?i:(?!not set)[a-z0-9.\\?!%, ])+$/) {
print " - yes matches\n";
}
else {
print " - no\n";
}
}
輸出:
' category1
' - 是匹配
' myCategory
' - 是匹配
' Hello World!!!
' - 是的比賽
' notset
' - 是的比賽
'' - 不
' not set
' - 沒有
' Not Set
' - 沒有
' NOT SET
' - 沒有
' <script>
' - 沒有
您可以嘗試以下代碼:
static void Main(string[] args)
{
string str = "NOT SET";
if (str.ToLower().Equals("not set"))
{
// Do Something
}
else
{
String pattern = @"^[a-z0-9.\?!%,]+$";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
if (regex.IsMatch(str))
{
// Do Something
}
}
}
我最終使用了
^(?![nN][oO][tT] [sS][eE][tT]$)[a-zA-Z0-9.?!%, ]+$
在我的.net驗證器和不顯眼的javascript中使用(?i :)時,我注意到我的客戶端驗證被禁用了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.