如何在 Visual Basic 中用正则表达式替换部分字符串

How to replace part of string with regular expression in Visual Basic

我需要替换部分字符串,一个是RGBA,另一个是RGB,都来自CSS style-sheet on Textbox in Visual Basic.

事情有点复杂,alpha 值变化,有时它有空格,我想正则表达式是更好的方法,但我不知道怎么做,让我举一些例子:

// RGBA
rgba(15,90,110,0.4);
rgba(15, 90,110, 0.2);
rgba(15, 90, 110, 0.35);
rgba(15, 90, 110,0.14);
rgba(15,90, 110,0.1) !important;
rgba(15,90, 110, 0.1);

// RGB
rgb(21, 25, 140);
rgb(21,25, 140);
rgb(21, 25,140);
rgb(21,25,140);
rgb(21, 25,140) !important;

// And so on...

我用来替换它的是 Visual Basic 中的 Replace 函数:

' RGBA
TextBox2.Text = TextBox1.Text.Replace("rgba(15,90,110,0.35)", "rgba(40,133,183,0.35)")

' RGB
TextBox2.Text = TextBox1.Text.Replace("rgb(21,25,140)", "rgb(40,175,81)")

当 alpha 值改变或它有空格时,问题就来了... 对于 RGB,我替换了每个间距选项,但我必须用不同的颜色来做,而且代码太长(每种颜色 4 行代码),有没有办法用正则表达式来做呢?

注意:我不替换它,包括 ; 因为有时它有 important 标志,所以我会保持原样,通过顺便说一下,我使用的是 Visual Studio 2012.

有人可以帮帮我吗?先谢谢你了。

尝试以下功能:

Private Function ReplaceRGBValue(ByVal i_sReplaceText As String, ByVal i_sOldRGBValue As String, ByVal i_sNewRGBValue As String) As String
    Dim sR As String = i_sOldRGBValue.Split(",")(0)
    Dim sG As String = i_sOldRGBValue.Split(",")(1)
    Dim sB As String = i_sOldRGBValue.Split(",")(2)
    Dim sPattern As String = "((?:rgba|rgb|RGBA|RGB)[ ]*\([ ]*)([ ]*" & sR & "[ ]*,[ ]*" & sG & "[ ]*,[ ]*" & sB & "[ ]*)(,[0-9 \.]+\)|\))"
    Dim sReplacement As String = "" & i_sNewRGBValue & ""
    Return System.Text.RegularExpressions.Regex.Replace(i_sReplaceText, sPattern, sReplacement)
End Function

正则表达式是:

(?:rgba|rgb|RGBA|RGB)[ ]*\([ ]* - 匹配大写或小写 rgb 或 rgba,后跟 0 个或多个 spaces,后跟开括号(转义),后跟 0 个或多个 spaces.

[ ]*" & sR & "[ ]*,[ ]*" & sG & "[ ]*,[ ]*" & sB & "[ ]* - 匹配 0 个或多个 space 以逗号分隔的数字

(,[0-9 \.]+\)|\)) - 匹配逗号后跟数字、小数点或 space,或者只是一个封闭的括号(转义)。

额外的括号是捕获组,您可以在 sReplacement.

中用 </code> 和 <code> 替换回字符串

像这样使用这个函数:

Dim sResult As String = ReplaceRGBValue("rgba(15,90,110,0.35)", "15,90,110", "40,133,183")

编辑:要批量进行替换,请尝试将此函数放入这样的 for 循环中:

  Private Sub BatchUpdate()
        ' Add more find/replace values to this array like {{"find,this,value","replace,with,this"}, _
        '                                                  {"also,find,this","and,replace,again"},...}
        Dim sReplacements(,) As String = {{"15,90,110", "40,133,183"}, _
                                          {"21,25,140", "40,175,81"}}
        Dim sResult As String = TextBox1.Text
        For i As Integer = 0 To UBound(sReplacements)
            sResult = ReplaceRGBValue(sResult, sReplacements(i, 0), sReplacements(i, 1))
        Next
        TextBox2.Text = sResult
    End Sub

希望有用。