Search code examples
c#regexstringlistmask

C# Get User Input Mask?


I am using C# and i Want to read some data that separated with some characters

for example : "IP@DOMAIN;USERNAME:PASSWORD"

but it's different in each list that user give

so i want to try to get the mast with a mask list the example

i use something like this to read the list

string[] lines = File.ReadAllLines("PathToTheList");
foreach(string line in lines){reading line with mask}

Solution

  • This can be solved with the following regex:

    "^([^@]+)@([^;]+);([^:]+):(.+)$"
    
    • ^ assert position at the start of the string
      • ([^@]+) capturing group for one or more characters, excluding '@' character (IP)
      • @ match '@' character
      • ([^;]+) capturing group for one or more characters, excluding ';' character (DOMAIN)
      • ; match ';' character
      • ([^:]+) capturing group for one or more characters, excluding ':' character (USERNAME)
      • : match ':' character
      • (.+) capturing group for one or more characters (PASSWORD)
    • $ assert position at the end of the string

    Regex regex = new Regex("^([^@]+)@([^;]+);([^:]+):(.+)$", RegexOptions.Compiled);
    
    string[] lines = File.ReadAllLines("PathToTheList");
    foreach (string line in lines)
    {
        Match match = regex.Match(line);
        if (match.Success)
        {
            GroupCollection groups = match.Groups;
            // group[0].ToString() == line
            string ip = groups[1].ToString();
            string domain = groups[2].ToString();
            string username = groups[3].ToString();
            string password = groups[4].ToString();
        }
    }