0

我尝试检查字符串是否包含任何字符,但不允许使用“\”和“^”。

Regex nameValidator = new Regex("^[\\^]+$"); 

这不起作用:

!nameValidator.IsMatch(myString)

为什么?

4

3 回答 3

1

因为字符类内部的 ^ 与外部具有不同的含义。这意味着对类字符的否定。所以我的正则表达式将允许除了\^

Regex nameValidator = new Regex(@"^[^^\\]+$");
于 2013-03-08T10:05:37.177 回答
0

试试这种方式:

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
于 2013-03-08T10:05:39.423 回答
0

\ 转义 C# 中字符串文字的反斜杠。因此,您的正则表达式(正如 regex engione 所见)是

^[\^]+$

这是有效的,但不是你想要的。(被关心的被反斜杠转义)更改为:

new Regex("[\\\\\\^]+");

或在字符串文字前使用 @(推荐)

new Regex(@"[\\\^]+"); 

您必须同时转义反斜杠和插入符号,因此使用三个反斜杠。要在没有@ 的字符串文字中使用它们,您必须再次转义每个反斜杠,因此您有六个。

于 2013-03-08T10:05:57.673 回答