[英]Globally negate and make case insensitive
有一個更好的方法嗎? 我無法弄清楚如何添加(?i)
所以我可以使模式全局不區分大小寫,同時仍然將語句保持為否定。
[Required(ErrorMessage = "Address")]
[RegularExpression("^(?!.*(p|P)\\.?(o|O)\\.?\\s+?(box|Box|BOX)).*$", ErrorMessage = "We cannot ship to PO boxes")]
public string CustomerAddress1 { get; set; }
我測試了這個,只是將(?i)
添加到開頭(如@sln所說)對我來說很好。
這是我的測試代碼,在控制台應用程序中:
static void Main(string[] args)
{
TestForPoBox("PO BOX 111");
TestForPoBox("P.O. Box 222");
TestForPoBox("p.O. boX 333");
TestForPoBox("444 Main Street");
Console.ReadKey();
}
static void TestForPoBox(string streetAddress)
{
const string pattern = "(?i)^(?!.*p\\.?o\\.?\\s+?box).*$";
Match match = Regex.Match(streetAddress, pattern);
//Write out the matches
if (match.Length > 0)
Console.WriteLine("OK. Address is not a P.O. Box: " + streetAddress);
else
Console.WriteLine("INVALID. Address contains a P.O. Box: " + streetAddress);
}
這是輸出:
INVALID. Address contains a PO Box: PO BOX 111 INVALID. Address contains a PO Box: PO Box 222 INVALID. Address contains a PO Box: pO boX 333 OK. Address is not a PO Box: 444 Main Street
(?i)...
表示不區分大小寫,而JavaScript支持/.../i
。
但兩種符號都不適用於另一種。
你可以做的最好的是你已經擁有的東西(拼寫出p|P
, o|O
等),或者像這里的SO答案中的Jeremy Cook的自定義RegularExpressionWithOptions
屬性。
您可以在比較期間對字符串使用.tolower()方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.