Regex in c#

laserpp

Distinguished
Nov 29, 2008
137
0
18,630
0
Hey all,

Not sure how to write the regex for just showing the usernames in this format: lastname,firstname. My searches are showing like user1, user2 ect and I dont want those, only want searches that are in that format.
 

randomizer

Distinguished
Moderator
Jul 24, 2006
880
0
19,260
62
What are you trying to do? Parse an existing string and rip out the last name and first name? You need to explain your problem in more detail, and give an example of some strings that you are working with. We can't read your mind or your screen.
 

majestic1805

Honorable
Oct 1, 2012
69
0
10,590
3
Well, to answer their question, code to match "lastname,firstname" would be:

[cpp]
// URL that generated this code:
// http://txt2re.com/index-csharp.php3?s=lastname,firstname&3&1&-25

using System;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string txt="lastname,firstname";

string re1="((?:[a-z][a-z]+))"; // Word 1
string re2="(,)"; // Any Single Character 1
string re3="((?:[a-z][a-z]+))"; // Word 2

Regex r = new Regex(re1+re2+re3,RegexOptions.IgnoreCase|RegexOptions.Singleline);
Match m = r.Match(txt);
if (m.Success)
{
String word1=m.Groups[1].ToString();
String c1=m.Groups[2].ToString();
String word2=m.Groups[3].ToString();
Console.Write("("+word1.ToString()+")"+"("+c1.ToString()+")"+"("+word2.ToString()+")"+"\n");
}
Console.ReadLine();
}
}
}

//-----
// Paste the code into a new Console Application
//-----
[/cpp]

A few resources on writing your own regex patterns:

http://en.wikipedia.org/wiki/Regular_expression
http://www.regular-expressions.info/
 

laserpp

Distinguished
Nov 29, 2008
137
0
18,630
0
Sorry, first here the the code I am working with. It forms a email list of all active users in our company with their lastname, firstname and email address. As you see I use a regex for the email to not bring in email addresses that start with Disabled. Now I need to get rid of names that arent in this format lastname, firstname. The comma is a big part of separating the users. For example I do not want contacts like Welligent Support, or User1, or Admin1 that are now populating the Name column.

Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices;
using Microsoft.Office.Interop.Excel;
using System.DirectoryServices.ActiveDirectory;
using System.DirectoryServices.AccountManagement;
using System.Threading;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;

namespace EmailListingFinal
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Opens the connection to the AD
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
            UserPrincipal qbeUser = new UserPrincipal(ctx);
            PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

            //Brings in the current user logged in first and last name
            string currentUserF = UserPrincipal.Current.GivenName;
            string currentUserL = UserPrincipal.Current.Surname;
            
            string[] lines = System.IO.File.ReadAllLines("C:\\names.txt");
            Regex rgx = new Regex("^(?![d,D]isabled)");
            //Regex rgx1 = new Regex(@"^(?=[A-Za-z])(?!.*[,._()\[\]-]{2})[A-Za-z._()\[\]-]$");
            int x;

                 
            //Security
            for (x = 0; x < lines.Length; x++)
            {
                if (currentUserF + " " + currentUserL == lines[x])
                {

                    int i = 0;
                    int y = 0;

                    //Loop that calculates how many entries are found
                    foreach (var found in srch.FindAll())
                    {
                        UserPrincipal foundUser = found as UserPrincipal;

                        if (foundUser != null && foundUser.EmailAddress != null && rgx.IsMatch(foundUser.EmailAddress))
                        {
                            string email = foundUser.EmailAddress;
                            string name = foundUser.DisplayName;
                            i++;
                        }
                    }

                    
                    //Function that creates the file that the names and emails will be written to
                    using (StreamWriter sw = File.CreateText("C:\\emailListing.txt"))
                    {
                        //Loop that goes through all the users in the AD
                        foreach (var found in srch.FindAll())
                        {
                            UserPrincipal foundUser = found as UserPrincipal;

                            //Loop that doesnt bring in users with no name or email address
                            if (foundUser != null && foundUser.EmailAddress != null && rgx.IsMatch(foundUser.EmailAddress))
                            {
                                //Gets the users name and email address
                                string email = foundUser.EmailAddress;
                                string name = foundUser.DisplayName;

                                //Writes the data to the txt file
                                sw.Write(name);
                                sw.Write(";  ");
                                sw.WriteLine(email);

                                //Function to make the progress bar load
                                progressBar1.Maximum = i;
                                progressBar1.Value = y++;


                            }


                        }

                        //Message that confirms the program has concluded
                        MessageBox.Show("Done - Please check C:\\emailListing.text to upload to excel using semicolon as the delimiter");
                        
                    }

                    System.Windows.Forms.Application.Exit();
                }

                

            }

           
                //Error message if the user doesn't match then exits the program
                MessageBox.Show("Unathorized User");
                System.Windows.Forms.Application.Exit();
            
                
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }
    }
}
 

ASK THE COMMUNITY