javascript - 正则表达式 javascript 到 vb

标签 javascript regex vb.net repeat

我有一个 JavaScript 函数 maxRepeat。我在将其转换为 vb.net 时遇到了麻烦,似乎正则表达式引擎有所不同......而且我对正则表达式不是那么强。您介意向我指出将正则表达式字符串转换为适当的 vb.net 字符串的正确方向吗? ...我明白如何做逻辑后记,只是迷失在正则表达式字符串上...

我正在谈论这个功能..

function maxRepeat(input) {
        var reg = /(?=((.+)(?:.*?\2)+))/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;
    }

此函数返回至少出现两次的最大字符序列。 “一二一三一四”将返回“一t”<--带有空格|| “onetwoonethirdonefour”将返回“onet”

“324234241122332211345435311223322112342345541122332211234234324”返回“1122332211234234”

最佳答案

首先,SO“不是转换服务”,但我自己也很好奇。其次,您的正则表达式完全可以在 VB.NET 中使用。第三,您可以利用 Regex.Matches 而不是按顺序检查匹配项。最后,您不能将变量命名为“sub”,它是 VB.NET 中的保留字。

现在,这是您在 VB.NET 中的函数:

Private Function maxRepeat(input As String) As String
   maxRepeat = String.Empty
   Dim reg As String = "(?=((.+)(?:.*?\2)+))"
   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 = "(?=((.+)(?:.*?\2)+))"
    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

关于javascript - 正则表达式 javascript 到 vb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29525467/

相关文章:

javascript - jQuery v1.6.4 无法识别 selectmenu(),错误 : "undefined is not a function"

php - 从 document.ready 调用 PHP

javascript - 如何使用 touchmove 来补充 mousemove for androids

c# - 确定两点是否接近

vb.net - 检查空字节

javascript - 类型错误 : Cannot read property &#39;location&#39; of undefined

regex - 使用 grep 查询选择性文件

javascript - String.replace() 不替换换行符(或任何东西,就此而言)

regex - 替换 abcde[退格键][退格键] -> abc

vb.net - 捕获一般异常时,如何判断原始异常类型?