我尝试检查字符串是否包含任何字符,但''和'^'是不允许的。
Regex nameValidator = new Regex("^[\^]+$");
这行不通:
!nameValidator.IsMatch(myString)
为什么?
因为字符类的^ inside与outside的含义不同。它意味着阶级角色的否定。我的正则表达式将允许除和
^
以外的所有元素
Regex nameValidator = new Regex(@"^[^^\]+$");
试试:
Regex nameValidator = new Regex(@"^[^^\]+$");
string sample_text = "hello world";
bool isMatch = nameValidator.IsMatch(sample_text); // true
sample_text = @"Hello ^ world ";
isMatch = nameValidator.IsMatch(sample_text); // false
转义c#中字符串字面值的反斜杠。因此你的正则表达式(正则表达式引擎看到的)是
^[^]+$
这是有效的,但不是您想要的。(被反斜杠转义)改变:
new Regex("[\\\^]+");
或在字符串字面值前使用@(推荐)
new Regex(@"[\^]+");
必须转义反斜杠和插入符号,所以是三个反斜杠。要在没有@的字符串字面值中使用它们,必须再次转义每个反斜杠,这样就有六个反斜杠。