regex .NET仅在>之间找到并替换下划线和<

时间:2015-09-30 22:33:31

标签: regex replace

我有一个字符串列表,如下所示:

<a href="http://blah.tld/Title_and_Title_by_-_Mr._John_Doe.html">Title_in_Title_by_-_Mr._John_Doe</a>

我需要在_SPACE之间的文字中用html">替换</a>

这样结果看起来像这样:

<a href="http://blah.tld/Title_and_Title_by_-_Mr._John_Doe.html">Title in Title by - Mr. John Doe</a>

我试图分两步完成: 首先只用.*html">(.*)<\/a.*&amp; ^.*>(.*)<.*&amp; .*>.*<.*^.*>.*<.* 然后进行更换,但返回总是不变,现在我被卡住了。

非常感谢任何帮助实现这一目标

2 个答案:

答案 0 :(得分:1)

我将如何做到.split它然后.replace它,不需要正则表达式。

Dim line as string = "<a href=""http://blah.tld/Title_and_Title_by_-_Mr._John_Doe.html"">Title_in_Title_by_-_Mr._John_Doe</a>"
Dim split as string() = line.split(">"c)
Dim correctString as String = split(1).replace("_"c," "c)
忙完了

这是string.replace article

虽然如果你必须使用正则表达式,这可能是一种更好的方法

Dim inputString = "<a href=""http://blah.tld/Title_and_Title_by_-_Mr._John_Doe.html"">Title_in_Title_by_-_Mr._John_Doe</a>"
Dim reg As New Regex("(?<=\>).*?(?=\<)")
Dim correctString = reg.match(inputString).value.replace("_"c, " "c)

答案 1 :(得分:0)

Dim line as string = "<a href=""http://blah.tld/Title_and_Title_by_-_Mr._John_Doe.html"">Title_and_Title_by_-_Mr._John_Doe</a>"

line = Regex.Replace(line, "(?<=\.html"">)[^<>]+(?=</a>)", _
    Function (m) m.Value.Replace("_", " "))

这使用带有lookarounds的正则表达式来隔离标题,并使用lambda表达式形式的MatchEvaluator委托来替换标题中的下划线,然后将结果插回到字符串中。