Gogo Gogo - 1 year ago 105
C# Question

c# String filtering and split with regex match

I'm trying to to filter strings with regex but i'm not that familiar with regex so i need a little help. Also i need to check if string contains specific regex part like example of input bellow:

Input (string):

"<value1;;value2;value3>Lorem ipsum dolor sit amet!"

If exist return these values:

string val1 = ????; //can't be null or empty, must be at least 3 chars/ints
string val2 = ????; //can be empty string
string val3 = ????; //can be empty string
string ipaddress = ????; // can't be empty
string text = ????; //can be empty string

Otherwise if not exist return only "lorem ipsum..." text:

string text = ????; //can be empty string

So first i need to check if that specific part exist in full string.
String can be without that part.

Can please someone explain me how I can do that?

EDIT: (please don't judge, i'm really bad with regex)
Here is what i tried:

private static bool ifContain(string a)
return Regex.IsMatch(a, @"([a-zA-Z0-9]*)\;([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:[0-9]{5})([a-zA-Z0-9*)\;([a-zA-Z0-9]*)\;([<a-zA-Z0-9]*)");

Answer Source

Here's a way combining regex and split. I did not do any null/empty/whitespace validation, nor did I validate that the split results contain at least 4 elements. This uses capture groups to select text from within the match, and it just blindly grabs all text it can in the groups using .*, where the groups are defined with the parenthesis.

        string txt = "<value1;;value2;value3>Lorem ipsum dolor sit amet!";
        var rgx = new Regex(@"<(.*)>(.*)");
        var match = rgx.Match(txt);
        // Should check if (match.Success) here and only continue if true
        var entireMatch = match.Groups[0]; // unused
        var firstCaptureGroup = match.Groups[1].Value; // Everything between < >
        var secondCaptureGroup = match.Groups[2].Value; // Everything after < >
        var split = firstCaptureGroup.Split(';');

        string val1 = split[0]; 
        string val2 = split[2]; 
        string val3 = split[3]; 
        string ipaddress = split[1]; 
        string text = secondCaptureGroup;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download