Check if string contains ip address

I have a file loaded in a stream reader. The file contains IP addresses scattered around. Before and after each IP address there is a "\" if that helps. In addition, the first "\" in each line ALWAYS comes before the ip-address, before the first there will be no other "\".

I already know that I should use a while loop to loop through each line, but I don't know the rest of the procedure: <

For instance:

Powerd by Stormix.de \ 93.190.64.150 \ 7777 \ False

Cupserver \ 85.236.100.100 \ 8178 \ False

Euro server \ 217.163.26.20 \ 7778 \ False

in the first example I will need "93.190.64.150" in the second example I will need "85.236.100.100", in the third example I will need "217.163.26.20"

I am really struggling with parsing / splicing / dicing: s

early

*** I need to save the IP address in a string, returning bool is not enough for what I want to do.

+3
source share
3 answers
using System.Text.RegularExpressions;


var sourceString = "put your string here";
var match = Regex.Match(sourceString, @"\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b");
if(matches.Success) Console.WriteLine(match.Captures[0]);

This will match any IP address, but also 999.999.999.999. If you need extra accuracy, see Details here: http://www.regular-expressions.info/examples.html

The site has a lot of interesting information about regular expressions, which are a domain-specific language that is used in most popular programming languages ​​to match text patterns. In fact, I think the site was compiled by the author of Mastering Regular Expressions .

Update

, IP-, ( IP-). , Success, IP- Captures[0] ( , , , 0).

+9

EDIT: " ".

( , split ).

\\(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\

Full sample:

using System;
using System.Text.RegularExpressions;

class Program
{
    private static readonly Regex Pattern = new Regex
        (@"\\(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}" +
         @"(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\");


    static void Main(string[] args)
    {
        Console.WriteLine(ContainsAddress("Bad IP \\400.100.100.100\\ xyz"));
        Console.WriteLine(ContainsAddress("Good IP \\200.255.123.100\\ xyz"));
        Console.WriteLine(ContainsAddress("No IP \\but slashes\\ xyz"));
        Console.WriteLine(ContainsAddress("Long IP \\123.100.100.100.100\\ x"));
    }

    static bool ContainsAddress(string line)
    {
        return Pattern.IsMatch(line);        
    }
}
+6

, "^.*?\\(?<address>[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\\.*$"

:

^ - , , .

. *? - , .

\ - . , .

(?) - , . , , , .

[0-9] {1,3} - 1 3 . [0-9] \d, , , , , .

. - .

. * - . .

$- .

+1
source

Source: https://habr.com/ru/post/1763846/


All Articles