在正则表达式替换字符串

时间:2016-06-24 22:12:11

标签: asp.net regex

我有一种情况需要从某些文本中删除HTML代码。但是,某些输入文本包含列表,我想在这种情况下保留编号。

如果我这样做

result = Regex.Replace(result, "<li>", vbNewLine & "1. ", RegexOptions.IgnoreCase)

然后在剥离其他HTML标签后,我最终得到:

1. List item one
1. List item two
1. List item three

有没有办法在替换期间获得匹配的索引?

所以例如:

result = Regex.Replace(result, "<li>", vbNewLine & replacementIndex + 1 & " ", RegexOptions.IgnoreCase)

然后在剥离其他HTML标签后,我会得到:

1. List item one
2. List item two
3. List item three

这可能吗?

注意:这是在一个函数内部,因此每个列表都是单独处理的,而无序列表则会得到项目符号(*)。

3 个答案:

答案 0 :(得分:0)

这应该是一个很好的起点。 @"(\<ul\>)((.|\n)*?)(\<\/ul\>)"这将匹配标记之间的所有内容。

答案 1 :(得分:0)

它很乱,但是类似于以下内容。一次只能更改一个。对于大型数据集,这可能会很慢。

int lineNbr = 1;
string newResult = result.Replace("(?i)<li>", vbNewLine & (lineNbr++).ToString() & '. ', 1);
while (newResult != result)
{
   result = newResult;
   newResult = result.Replace("(?i)<li>", vbNewLine & (lineNbr++).ToString() & '. ', 1);
}

答案 2 :(得分:0)

这就是我最终要做的事情-首先,找到每个有序列表:

Dim result As String = rawText
Dim orderedLists As MatchCollection = Regex.Matches(rawText, "<ol>.*?</ol>", RegexOptions.Singleline)

For Each ol As Match In orderedLists
    result = Replace(result, ol.Value, EncodeOrderedList(ol.Value))
Next

以及转换每个函数的函数:

Private Function EncodeOrderedList(ByVal rawText As String) As String
    Dim result As String = rawText
    result = Regex.Replace(result, "<ol>\s*<li>", "1. ", RegexOptions.IgnoreCase)
    result = Regex.Replace(result, "</li>\s*</ol>", vbNewLine & vbNewLine, RegexOptions.IgnoreCase)
    Dim bullets As MatchCollection = Regex.Matches(rawText, "</li>\s*<li>")
    Dim i As Integer = 2
    For Each li As Match In bullets
        result = Replace(result, li.Value, vbNewLine & i & ". ", 1, 1)
        i += 1
    Next

    Return result
End Function

我还没有在嵌套列表中对其进行测试。

相关问题