Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何创建不允许反斜杠的正则表达式_C#_Regex - Fatal编程技术网

C# 如何创建不允许反斜杠的正则表达式

C# 如何创建不允许反斜杠的正则表达式,c#,regex,C#,Regex,我在创建正则表达式以禁止以下四个字符并限制大小时遇到问题: / # ? \ 我目前拥有的是: Regex regex = new Regex("^[^/\\#?]{0,1024}$", RegexOptions.Compiled); if (!regex.IsMatch("\\")) { Console.WriteLine("Bad"); } 不允许使用除\以外的所有字符。我不能上班了 关于如何支持这一点,您有什么建议吗?您很接近,需要避开反斜杠: ^[^/\\\\\\?]{01024

我在创建正则表达式以禁止以下四个字符并限制大小时遇到问题:

/ # ? \

我目前拥有的是:

Regex regex = new Regex("^[^/\\#?]{0,1024}$", RegexOptions.Compiled);
if (!regex.IsMatch("\\"))
{
    Console.WriteLine("Bad");
}
不允许使用除\以外的所有字符。我不能上班了


关于如何支持这一点,您有什么建议吗?

您很接近,需要避开反斜杠:

^[^/\\\\\\?]{01024}$


即使不需要转义字符类中的特殊字符,也需要转义字符本身。

尝试两个前斜杠

^[^/\\\\\?]{01024}$

在C++中,前向斜杠是为转义字符保留的,如<代码> \n>代码>。要生成文字正斜杠,请使用
\\

您的正则表达式很好,
^[^/\\\\\\\\?]{01024}$

但是在C中,反斜杠是转义字符,所以C
“\\”
是单个反斜杠。 因此,对于正则表达式中的每个反斜杠,必须再次反斜杠表示C#:

或者,您可以使用原始字符串,这意味着C#字符串中的反斜杠仍然是反斜杠(请注意
@
符号):

Regex regex = new Regex("^[^/\\\\#?]{0,1024}$", RegexOptions.Compiled);
Regex regex = new Regex(@"^[^/\\#?]{0,1024}$", RegexOptions.Compiled);