正则表达式 javascript 到 vb

Regex javascript to vb

我有一个 javascript 函数 maxRepeat。我在将它翻译成 vb.net 时遇到了问题,似乎正则表达式引擎有所不同...而且我对正则表达式的处理能力不强。您介意向我指出将正则表达式字符串翻译成适当的 vb.net 的正确方向吗? ...我明白如何做后记的逻辑,只是迷失在正则表达式字符串中...

我说的是这个功能..

function maxRepeat(input) {
        var reg = /(?=((.+)(?:.*?)+))/g;
        var sub = ""; 
        var maxstr = ""; 
        reg.lastIndex = 0; 
        sub = reg.exec(input); 
        while (!(sub == null)) {
            if ((!(sub == null)) && (sub[2].length > maxstr.length)) {
                maxstr = sub[2];
            }
            sub = reg.exec(input);
            reg.lastIndex++; 
        }
        return maxstr;
    }

这函数 returns 至少出现两次的最大字符序列。 "one two one three one four" 会 return "one t" <--with space || "onetwoonethreeonefour" 会 return "onet"

"324234241122332211345435311223322112342345541122332211234234324" returns "1122332211234234"

首先,SO "is not a converting service",但我自己很好奇。其次,您的正则表达式完全可以用于 VB.NET。第三,您可以利用 Regex.Matches 而不是按顺序检查匹配项。最后,变量不能命名为'sub',它是VB.NET.

中的保留字

现在,这是您在 VB.NET 中的功能:

Private Function maxRepeat(input As String) As String
   maxRepeat = String.Empty
   Dim reg As String = "(?=((.+)(?:.*?)+))"
   For Each m As Match In Regex.Matches(input, reg)
      If m IsNot Nothing And m.Groups(2).Value.Length > maxRepeat.Length Then
           maxRepeat = m.Groups(2).Value
      End If
   Next
End Function

或者,使用 LINQ(不要忘记 System.Linq 参考):

Private Function maxRepeat(input As String) As String
    maxRepeat = String.Empty
    Dim reg As String = "(?=((.+)(?:.*?)+))"
    Dim matches As IEnumerable(Of Match) = Regex.Matches(input, reg).Cast(Of Match)().Select(Function(m) m)
    maxRepeat = (From match In matches
                Let max_val = matches.Max(Function(n) n.Groups(2).Value.Length)
                Where match.Groups(2).Value.Length = max_val
                Select match.Groups(2).Value).FirstOrDefault()
End Function

函数调用方式如下:

Dim res As String = maxRepeat("324234241122332211345435311223322112342345541122332211234234324")

结果:

1122332211234234