我想计算具有特殊符号(下划线)的链接。我已经编写了正则表达式,它在在线编辑器/php 编辑器中工作正常,但在 C# 代码中不起作用:
<
(?<Tag_Name>(a)|img)\b
[^>]*?
\b(?<URL_Type>(?(2)href|src))
\s*=\s*
(?:"(?<URL>(?:\\.|[^\\"_#?&]++)*(?:_|(?<Query>[#?&]))(?:\\.|[^"\\]++)*)"
| '(?<URL>(?:\\.|[^\\'_#?&]++)*(?:_|(?<Query>[#?&]))(?:\\.|[^'\\]++)*)')
但在 C# 代码中它给出了编译错误
MatchCollection underscoreLinks = Regex.Matches(strIn, "<(?<Tag_Name>(a)|img)\b[^>]*?\b(?<URL_Type>(?(2)href|src)) \s*=\s*(?:"(?<URL>(?:\\.|[^\\"_#?&]++)*(?:_|(?<Query>[#?&]))(?:\\.|[^"\\]++)*)"| '(?<URL>(?:\\.|[^\\'_#?&]++)*(?:_|(?<Query>[#?&]))(?:\\.|[^'\\]++)*)')", RegexOptions.IgnoreCase | RegexOptions.Multiline);
请您参考如下方法:
有些地方你需要更正:
- 您使用的是单反斜杠,它们在传递给正则表达式之前由 .net 解释器解析。使用verbatim string相反,即:
@"pattern" - 您的字符串中有未转义的引号。要在逐字字符串中转义它们,请使用 2 double quotes :
@"the ""pattern""with quotes". - .net不支持 possessive quantifiers .使用 atomic group反而。即:将
[^\\"_#?&]++更改为(?>[^\\"_#?&]+)。 - 您可以使用相同的多行语法,忽略空格,使用
RegexOptions.IgnorePatternWhitespace.
string pattern = @"
<
(?<Tag_Name>(a)|img)\b
[^>]*?
\b(?<URL_Type>(?(2)href|src))
\s*=\s*
(?:""(?<URL>(?>\\.|[^\\""_#?&]+)*(?:_|(?<Query>[#?&]))(?>\\.|[^""\\]+)*)""
| '(?<URL>(?>\\.|[^\\'_#?&]+)*(?:_|(?<Query>[#?&]))(?>\\.|[^'\\]+)*)')
";
Regex re = new Regex( pattern,
RegexOptions.IgnoreCase | RegexOptions.Multiline
| RegexOptions.IgnorePatternWhitespace);
MatchCollection underscoreLinks = re.Matches(text);
