Reputation: 13
I have a javascript function maxRepeat. Im having trouble translating it to vb.net, seems regex engine differs...and Im not so strong on regex. Would you mind pointing me in the right direction for translating the regex string to the appropriate vb.net one ? ...I understand how to do the logic afterwords, just lost on the regex string...
Im talking about this function..
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;
}
This functions returns the largest sequence of characters that appear at least twice. "one two one three one four" would return "one t" <--with space || "onetwoonethreeonefour" would return "onet"
"324234241122332211345435311223322112342345541122332211234234324" returns "1122332211234234"
Upvotes: 1
Views: 518
Reputation: 627190
First, SO "is not a converting service", but I got curious myself. Second, your regex is totally fine for use in VB.NET. Third, you can leverage Regex.Matches
rather than checking matches sequentially. And lastly, you cannot name a variable 'sub', it is a reserved word in VB.NET.
Now, this is your function in 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
Or, with LINQ (do not forget System.Linq
reference):
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
The function may be called the following way:
Dim res As String = maxRepeat("324234241122332211345435311223322112342345541122332211234234324")
Result:
1122332211234234
Upvotes: 1