Zoplax
asked on
Regular Expressions
I need the exact regular expressions syntax to do the following. Here is the input statement:
server=myServer;database=m yDatabase; 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=m yDatabase;
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.
server=myServer;database=m
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=m
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.
(server|database)[^;]*;
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Try this
string s = "server=myServer;User Id=myuser;database=myDatab ase;pwd=my pass;";
string result = Regex.Replace(s, @"(?!(server|database)=)\b [^=;]+\b=[ ^;]+(;|$)" ,"");
string s = "server=myServer;User Id=myuser;database=myDatab
string result = Regex.Replace(s, @"(?!(server|database)=)\b
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
This Regex will do what you want and will find them in any order that they may be inputted.
string input = "server=myServer;database=
string output = string.Empty;
MatchCollection mc = Regex.Matches(input, @"((?:server|database)\s*=
RegexOptions.IgnoreCase);
foreach( Match m in mc )
{
output += m.Groups[1].Value + ";";
}
// The variable output will contain "server=myServer;database=
MessageBox.Show(output);
Fernando