有这样的一系列用分号分开的ip地址
10.92.221.19;10.92.221.20;10.92.221.21;10.92.221.23;10.92.221.24;10.92.221.25;10.92.221.26;10.92.221.27;10.92.221.28;10.92.221.29;10.92.221.30;10.92.221.31;10.92.221.32
现在需要将连续的ip地址进行优化显示,变成
10.92.221.19-21;10.92.221.23-32
js
let str = '10.92.221.19;10.92.221.20;10.92.221.21;10.92.221.23;10.92.221.24;10.92.221.25;10.92.221.26;10.92.221.27;10.92.221.28;10.92.221.29;10.92.221.30;10.92.221.31;10.92.221.32'
let arr = str.split(';');
let strs = '';
let num = 0;
arr.forEach((val,index) => {
let number = Number(val.replace(/./g, ''));
if (index === 0) {
strs += val + '-';
num = number
} else if (index === arr.length - 1) {
strs += val
} else {
if (num !== number - index) {
strs += arr[index-1] + ';' + val + '-'
num = number - index
}
}
})
console.log(strs);
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace Q769839
{
class Program
{
static void Main(string[] args)
{
string s = "10.92.221.19;10.92.221.20;10.92.221.21;10.92.221.23;10.92.221.24;10.92.221.25;10.92.221.26;10.92.221.27;10.92.221.28;10.92.221.29;10.92.221.30;10.92.221.31;10.92.221.32";
var query = s.Split(';').Select(x => x.Split('.')).OrderBy(x => x[0]).ThenBy(x => x[1]).ThenBy(x => x[2]).ThenBy(x => x[3]).ToList();
List<string> list = new List<string>();
string[] pre = query[0];
for (int i = 1; i < query.Count; i++)
{
if (string.Join(".", query[i].Take(3)) == string.Join(".", query[i - 1].Take(3)) && int.Parse(query[i][3]) - int.Parse(query[i - 1][3]) != 1)
{
if (query[i - 1] != pre)
list.Add(string.Join(".", pre) + "~" + query[i - 1][3]);
else
list.Add(string.Join(".", pre));
pre = query[i];
}
}
if (query[query.Count - 1] != pre)
list.Add(string.Join(".", pre) + "~" + query[query.Count - 1][3]);
else
list.Add(string.Join(".", pre));
foreach (var item in list)
Console.WriteLine(item);
}
}
}
10.92.221.19~21
10.92.221.23~32
Press any key to continue . . .
哈哈,自己用VB早就解决了,只是想看看有没有更好的思路
vbscript:
iprgz = "10.92.221.19;10.92.221.20;10.92.221.21;10.92.221.23;10.92.221.24;10.92.221.25;10.92.221.26;10.92.221.27;10.92.221.28;10.92.221.29;10.92.221.30;10.92.221.31;10.92.221.32"
iprglst = Split(iprgz, ";")
niprgz = Split(iprgz, ";")(0)
phost = Split(niprgz, ".")(3)
For i = 1 To UBound(iprglst)
chost = Split(iprglst(i), ".")(3)
If Val(chost) - Val(phost) <> 1 Then
niprgz = niprgz & "-" & phost & ";" & iprglst(i)
End If
phost = chost
Next
If phost - Split(iprglst(i - 2), ".")(3) = 1 Then niprgz = niprgz & "-" & phost
Debug.Print niprgz