这个问题在这里已有答案:
需要使用正则表达式从以下url <a href="http://example.com">Name</a>
中删除a标记,以仅输出字符串"Name"
。我正在使用C#.net。
任何帮助表示赞赏
这样做会很好:
str = Regex.Replace(str, @"<a\b[^>]+>([^<]*(?:(?!</a)<[^<]*)*)</a>", "$1");
你应该看看Html Agility Pack。 RegEx适用于几乎所有情况,但它失败了一些基础知识或破坏了Html。由于HTML的语法不规则,Html Agility包在所有情况下仍然可以完美地运行。
如果您只是寻找锚标记这一特定情况的一次,任何以上RegEx都适合您,但Html Agility Pack是您的长期,可靠的解决方案,以剥离任何Html标签。
你可以尝试使用这个。它尚未在所有条件下进行测试,但它将从您的示例中返回正确的值。
\<[^\>]+\>(.[^\<]+)</[^\>]+\>
这是一个仅适用于标签的版本。
\<a\s[^\>]+\>(.[^\<]+)</a\>
我在以下HTML上测试它,它只返回Name和Value。
<a href="http://xx.com">Name</a><label>This is a label</label> <a href="http://xx.com">Value</a>
同意Priyank使用解析器是一个更安全的赌注。如果您确实使用正则表达式的路线,请考虑如何处理边缘情况。您可以轻松转换您在问题中提到的简单案例。如果这确实是标记将采用的唯一形式,那么一个简单的正则表达式就可以处理它。但是,如果标记是,例如,用户生成的或来自第三方源,请考虑以下情况:
<a>foo</a> --> foo # a bare anchor tag, with no attributes
# the regexes listed above wouldn't handle this
<a href="blah"><b>boldness</b></a> --> <b>boldness</b>
# stripping out only the anchor tag
<A onClick="javascript:alert('foo')">Upper\ncase</A> --> Upper\ncase
# and obviously the regex should be case insensitive and
# apply to the entire string, not just one line at a time.
<a href="javascript:alert('<b>boom</b>')"><b>bold</b>bar</a> --> <b>bold</b>bar
# cases such as this tend to break a lot of regexes,
# if the markup in question is user generated, you're leaving
# yourself open to the risk of XSS
以下是为我工作。
Regex.Replace(inputvalue, "\<[\/]*a[^\>]*\>", "")