我尝试检查字符串是否包含任何字符,但不允许使用“\”和“^”。
Regex nameValidator = new Regex("^[\\^]+$");
这不起作用:
!nameValidator.IsMatch(myString)
为什么?
我尝试检查字符串是否包含任何字符,但不允许使用“\”和“^”。
Regex nameValidator = new Regex("^[\\^]+$");
这不起作用:
!nameValidator.IsMatch(myString)
为什么?
因为字符类内部的 ^ 与外部具有不同的含义。这意味着对类字符的否定。所以我的正则表达式将允许除了\
和^
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# 中字符串文字的反斜杠。因此,您的正则表达式(正如 regex engione 所见)是
^[\^]+$
这是有效的,但不是你想要的。(被关心的被反斜杠转义)更改为:
new Regex("[\\\\\\^]+");
或在字符串文字前使用 @(推荐)
new Regex(@"[\\\^]+");
您必须同时转义反斜杠和插入符号,因此使用三个反斜杠。要在没有@ 的字符串文字中使用它们,您必须再次转义每个反斜杠,因此您有六个。