1

我在我的 EF 元数据上使用RegularExpressionAttribute ,如下所示:

[RegularExpression("[A-Z]+")]
public string Code { get; set; }

它正确地不允许我在该字段的任何地方输入除 AZ 以外的任何内容。

在其他地方我想在代码中使用相同的 reg 表达式,所以我像这样转向 Regex:

var regex = new Regex("[A-Z]+");
Console.WriteLine(regex.IsMatch("B")); //true
Console.WriteLine(regex.IsMatch("1")); //false
Console.WriteLine(regex.IsMatch("A1")); //true - why?

RegexStringValidator的工作方式也与 Regex 相同。

我究竟做错了什么?

4

3 回答 3

4
var regex = new Regex("[A-Z]+");
Console.WriteLine(regex.IsMatch("A1")); //true - why?

该正则表达式表示匹配一个或多个大写拉丁字母。并且“ A1”包含一个大写的拉丁字母。

默认情况下,正则表达式匹配字符串中的任何位置。要匹配整个字符串以字符串锚点的“ ^开头并以字符串锚点的“ $结尾结尾

 var regex = new Regex("^[A-Z]+$");
 Console.WriteLine(regex.IsMatch("A1")); 

将显示false

(.NET 正则表达式中有一整套。)

于 2012-07-25T14:01:51.897 回答
1

可能你想要这个:

"^[A-Z]+$"

"[A-Z]+"将匹配一个或多个字母,不管它们在字符串中的位置。

于 2012-07-25T14:00:19.420 回答
0

你必须锚定你的正则表达式

"^[A-Z]$"
于 2012-07-25T14:00:20.533 回答