我有一个regex表达式来检查字符串是否包含IP地址。
我有没有检查过,并删除了任何端口号/ipv6 6的细节-所以我只剩下IP地址:
117.89.65.117.ipv6.la应该变成117.89.65.117
121.58.242.206:449应该变成121.58.242.206
到目前为止,这是我想出的要检查的代码--有人能帮我把上面的额外信息删除吗?
private void AddToList(String IP)
{
Regex ipAddress = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
Match result = ipAddress.Match(IP);
if (chkQuotes.Checked) IP = "\"" + IP + "\"";
if (result.Success)
if (cIPlist.IndexOf(IP) <= 0)
cIPlist.Add(IP);
}发布于 2018-11-05 11:00:25
您可以使用result.Value访问整个匹配值,而不是重新使用IP变量。
另外,在方法中使用正则表达式来加快速度之前,最好先定义正则表达式。
private static HashSet<string> cIPlist = new HashSet<string>();
private static readonly Regex ipAddress = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
private void AddToList(String IP)
{
var result = ipAddress.Match(IP);
if (result.Success) # Check if there is a match
{
if (chkQuotes.Checked) # If the checkbox is checked
{
IP = $"\"{result.Value}\""; # Add quotes around the match value
}
cIPlist.Add(IP); # Add to hashset of strings
}
}见C#演示。
请注意,如果您希望将regex模式限制为只匹配IPs,而不匹配像999.999.999.999这样的字符串,则可以使用来自regular-expressions.info的著名模式。
new Regex(@"\b(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}\b")发布于 2018-11-05 10:58:30
首先,我们可以使用https://www.regular-expressions.info/ip.html修复正则表达式,并将其减少一点。用(){3}。
然后,为了消除重复,您可以使用不允许重复的HashSet<string>。
为了添加“简单”一行linQ,为了进行测试,我将AddToList参数转换为params string[]。
static HashSet<string> resultingList = new HashSet<string>();
static string pattern = @"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]";
static Regex ipRegex = new Regex(pattern);
static void AddToList(params string[] ips) =>
resultingList.UnionWith(
ips.Select(x => ipRegex.Match(x))
.Where(x => x.Success)
.Select(x => x.Value)
);
private static void TestMethod()
{
var inputs = new[]{
"123.123.123.13:256",
"123.123.123.13:256", //duplicate line
"17.89.65.117.ipv6.la ",
"21.58.242.206:449",
"666.666.666.666"
};
AddToList(inputs);
AddToList("127.0.0.1");
}https://stackoverflow.com/questions/53152266
复制相似问题