Link to home
Start Free TrialLog in
Avatar of Zoplax
Zoplax

asked on

Regular Expressions

I need the exact regular expressions syntax to do the following.  Here is the input statement:

      server=myServer;database=myDatabase;User Id=myuser;pwd=mypass;

I need to make it so that my regex statement will trigger a match for only the "server" and "database" portions of the string above.  In other words, it should return a match AS IF it sees a string like this:

      server=myServer;database=myDatabase;

I found a regex which almost does what I want, this returns a match on each name/value pair for each of the four (4) sets.

      (.+?)(?:=)(.+?)(?:;|$)

I need to modify this so that it only grabs a match for "server" and "database", but I don't see how (or if it's even possible) to match based on groups of words.

Avatar of ozymandias
ozymandias
Flag of United Kingdom of Great Britain and Northern Ireland image

(server|database)[^;]*;
ASKER CERTIFIED SOLUTION
Avatar of ozymandias
ozymandias
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of joechina
joechina

Try this
string s = "server=myServer;User Id=myuser;database=myDatabase;pwd=mypass;";
string result = Regex.Replace(s, @"(?!(server|database)=)\b[^=;]+\b=[^;]+(;|$)","");
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Fernando Soto
Hi Zoplax;

This Regex will do what you want and will find them in any order that they may be inputted.

      string input = "server=myServer;database=myDatabase;User Id=myuser;pwd=mypass;";
      string output = string.Empty;
      MatchCollection mc = Regex.Matches(input, @"((?:server|database)\s*=\s*.+?)(?:;|$)",
            RegexOptions.IgnoreCase);
      foreach( Match m in mc )
      {
            output += m.Groups[1].Value + ";";
      }

      // The variable output will contain "server=myServer;database=myDatabase;"
      MessageBox.Show(output);


Fernando