带点和引号的正则表达式模式

时间:2014-02-10 13:46:41

标签: c# .net regex

如何在c#中声明正则表达式模式。模式以引号开头,后来是url地址,有些东西如下

\"www\.mypage\.pl  //<- this is my pattern

string pattern = ? //todo: what should I put there

3 个答案:

答案 0 :(得分:1)

使用逐字字符串:

string pattern = @"""www\.mypage\.pl";

答案 1 :(得分:0)

您可以使用\反斜杠来转义正则表达式语义并恢复为实际文字。如果你想逃避

"www.mypage.pl

你可以使用

\"[0-9a-zA-Z]*\.[0-9a-zA-Z]*\.[0-9a-zA-Z]*
^ this is not to escape the regex but the eventual string
  if you use single quotes you don't need to escape the quotes!

请注意,[0-9a-zA-Z]*需要更多字符,例如%-以及_,以根据关于网址的 RFC 捕获所有案例我现在无法生成的语法(很容易在网上找到)。

如果你想逃避

\"www\.mypage\.pl

你也必须逃脱逃脱:

\\\"[0-9a-zA-Z]*\\\.[0-9a-zA-Z]*\\\.[0-9a-zA-Z]*

答案 2 :(得分:0)

其他答案已经处理过(非常好)如何将短语本身放入字符串中。

要使用它,您需要引用System.Text.RegularExpressions命名空间,其文档为over at MSDN。作为(非常)快速的例子:

System.Text.RegularExpressions.Regex.Replace(content,
                                        regexPattern, newMatchContent);

regexPattern中的正则表达式content的匹配项替换为newMatchContent,并返回结果。

相关问题