Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/257.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,我有一个正则表达式,现在需要移到C。我会犯这样的错误 Unrecognized escape sequence 我使用的是Regex.Escape,但显然不正确 string pattern = Regex.Escape("^.*(?=.{7,})(?=.*[a-zA-Z])(?=.*(\d|[!@#$%\?\(\)\*\&\^\-\+\=_])).*$"); hiddenRegex.Attributes.Add("value", pattern); 这是如何正确完成的?您在

我有一个正则表达式,现在需要移到C。我会犯这样的错误

Unrecognized escape sequence    
我使用的是Regex.Escape,但显然不正确

string pattern = Regex.Escape("^.*(?=.{7,})(?=.*[a-zA-Z])(?=.*(\d|[!@#$%\?\(\)\*\&\^\-\+\=_])).*$");
hiddenRegex.Attributes.Add("value", pattern);

这是如何正确完成的?

您在编译时遇到的错误是否正确?这意味着C#编译器无法理解您的字符串。在字符串前面加上@符号,你应该会没事的。你不需要Regex.Escape


您得到的错误是在编译时出现的,对吗?这意味着C#编译器无法理解您的字符串。在字符串前面加上@符号,你应该会没事的。你不需要Regex.Escape


出现错误的原因是字符串包含无效的转义序列(例如
\d
)。要解决此问题,请手动转义反斜杠,或改为写入:

Regex.Escape
用于将动态内容嵌入正则表达式,而不是用于构造固定正则表达式。例如,您可以在此处使用它:

string name = "this comes from user input";
string pattern = string.Format("^{0}$", Regex.Escape(name));

之所以这样做,是因为
name
很可能包含正则表达式中具有特殊含义的字符,例如点或括号。当
name
为硬编码时(如您的示例中),您可以手动转义这些字符。

您得到的错误是由于您的字符串包含无效的转义序列(例如
\d
)。要解决此问题,请手动转义反斜杠,或改为写入:

Regex.Escape
用于将动态内容嵌入正则表达式,而不是用于构造固定正则表达式。例如,您可以在此处使用它:

string name = "this comes from user input";
string pattern = string.Format("^{0}$", Regex.Escape(name));

之所以这样做,是因为
name
很可能包含正则表达式中具有特殊含义的字符,例如点或括号。当
name
硬编码时(如您的示例中),您可以手动转义这些字符。

Regex。转义是转义正则表达式模式中的特殊字符,以便它们与输入中的逐字匹配。转义错误用于语言编译。\需要在字符串中转义。不仅仅是正则表达式!!必须使用\或使用@
Regex进行转义。转义是转义Regex模式中的特殊字符,以便它们与输入中的逐字匹配。转义错误用于语言编译。\需要在字符串中转义。不仅仅是正则表达式!!必须使用\或使用转义@
string name = "this comes from user input";
string pattern = string.Format("^{0}$", Regex.Escape(name));