日期:2014-05-20  浏览次数:20984 次

正则表达式替换内容(VB.NET)
因为考虑到性能问题,所以想把现有代码中类似
VB.NET code

If str1 = "" AndAlso str2 = "" Then
    ...
End If

If str1 = "" OrElse str2 = "" Then
    ...
End If


的方式用如下方式替换
VB.NET code

If str1.Length = 0 AndAlso str2.Length = 0 Then
    ...
End If

If str1.Length = 0 OrElse str2.Length = 0 Then
    ...
End If


因为需要替换的地方比较多,所以考虑使用正则表达式的反向引用方式替换,但是小弟不才,只能使用替换如下代码
VB.NET code

Dim rg8 As Regex = New Regex("^If\s(?<key>\w+)\s=\s""\sThen")
Console.WriteLine(rg8.Replace("If str = "" Then", "If ${key}.Length = 0 Then"))
'Output:If str.Length = 0 Then


如果If条件中有多个AndAlso、OrElse或者两者混合,再复杂点的还有括号如下:
VB.NET code

If str1 = "" AndAlso (str2 = "" OrElse str3 = "" ) OrElse str4 = "" Then
    ...
End If


所以,请教高手,遇到这些复杂条件的If语句,该如何使用正则表达式替换呢?

------解决方案--------------------
你要考虑当str1为Nothing时
str1=""仍然有用
但str1.Length = 0就异常了
------解决方案--------------------
C# code

void Main()
{
    string str=@"If str1 = """" AndAlso str2 = """" Then
    ...
End If

If str1 = """" OrElse str2 = """" Then
    ...
End If

If str1 = """" AndAlso (str2 = """" OrElse str3 = """" ) OrElse str4 = """" Then
    ...
End If";
    str=Regex.Replace(str,@"(If|AndAlso|OrElse)\s+((\S+)\s*=\s*"""")","$1 $3.Length = 0");
    Console.WriteLine(str);
    /*
    If str1.Length = 0 AndAlso str2.Length = 0 Then
    ...
End If

If str1.Length = 0 OrElse str2.Length = 0 Then
    ...
End If

If str1.Length = 0 AndAlso (str2.Length = 0 OrElse str3.Length = 0 ) OrElse str4.Length = 0 Then
    ...
End If

    */
}

------解决方案--------------------
不用什么都想着一步全天,直接用DW批量分别替换,比起你写正则的时间要效率得多
If str1 = "" AndAlso str2 = "" Then

If str1 = "" OrElse str2 = "" Then