I have a string in the format:
PROVIDER=Sybase.ASEOLEDBProvider.2;User ID=sa;Server Name=UKServer;Server Port Address=5001;Initial Catalog=master
Using a regular expression in C# now can I get the value of Server Name?
Please note that Server Name could be in any location in the string and there may or may not be a space either side of the "=" i.e. the fomate could be
... Server Name=UKServer;....
... Server Name = UKServer;....
... Server Name =UKServer;....
... Server Name= UKServer;....
You don't really have to the parse the connection-string yourself; the handy OdbcConnectionStringBuilderclass can do it for you. It implementsIDictionary, allowing you retrieve all of the attributes of the connection-string by key. I'm sure it is reasonably resistant to the different kinds of input that you mention, e.g. additional white-space, different ordering of key-vale pairs, etc.
Here's an example, tested for your sample:
var connString = #"PROVIDER=Sybase.ASEOLEDBProvider.2;User ID=sa;Server Name=UKServer;Server Port Address=5001;Initial Catalog=master";
var connStringBuilder = new OdbcConnectionStringBuilder(connString);
var serverName = connStringBuilder["Server Name"].ToString();
_serverName = RegEx.Match(inputString, "Server Name ?= ?([\\w]+);").Groups(1).Value;
Breakdown:
Server Name ?= ? // Normal string, the ? means that the preceding character
// or group is optional (0 or 1)
([\w]+); // The parentheses define a group (the Group(0) is the
// always the whole match), so that you can easily get a
// substring of the match.
[\w]+ // Matches any alphabetical character, number or underscore
Something like this should work:
"Server Name\s*=\s*(\w+)\s*;"
How about something like this :
[^&]*(i?)(Server Name\s|)((i?)[a-z]);
_serverName = RegEx.Match(inputString, "[^&]*(i?)(Server Name\s|)((i?)[a-z]);").Groups(2).Value;
Related
I am a C#.net developer.
I wanted to check if a source string contained all of the characters in the destination string.
ex:
Source String : Test Check
Destination sting : Check Test
Then wanted to check if each char(T,e,s,t,c,h,e,c,k) are present in the destination string?
The source string can contain numeric/alphanumeric/special characters to compare with destination string.
We can verify by loop through each & every character from the destination and match that to destination but that would takes time.
Is there any simple way to check this?
You can use linq All method for this
string source = "Test Check";
string destination = "Check Test;
bool result = source.All(a => destination.Contains(a));
As #GrantWinney mentioned this solution won't take the number of letter occurences into consideration
You can use Except + Any:
string sourceString ="Test Check";
string destString ="Check Test";
bool destStringContainsSource = !sourceString.Except(destString).Any();
or with HashSet.SetEquals:
HashSet<char> set = new HashSet<char>(sourceString);
destStringContainsSource = set.SetEquals(destString);
Both approaches don't take the number of characters into account.
The Except-approach does not even check if the destination-string contains more characters. It's just checking if the second string is a subset of the first. SetEquals is not quite the same.
You can use HashSet.IsSubsetOf to get the same behaviour:
HashSet<char> set = new HashSet<char>(sourceString);
bool sourceIsSubsetOfDest = set.IsSubsetOf(destString);
I would prefer the HashSet approaches since they are very efficient and most of all clear.
Hi all I want to know something regarding to fixed-string in regular expression.
How to represent a fixed-string, regardless of special characters or alphanumeric in C#?
For eg; have a look at the following string:
infinity.world.uk/Members/namelist.aspx?ID=-1&fid=X
The entire string before X will be fixed-string (ie; the whole sentence will appear the same) BUT only X will be the decimal variable.
What I want is that I want to append decimal number X to the fixed string. How to express that in terms of C# regular expression.
Appreciate your help
string fulltext = "inifinity.world.uk/Members/namelist.aspx?ID=-1&fid=" + 10;
if you need to modify existing url, dont use regex, string.Format or string.Replace you get problem with encoding of arguments
Use Uri and HttpUtility instead:
var url = new Uri("http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=X");
var query = HttpUtility.ParseQueryString(url.Query);
query["fid"] = 10.ToString();
var newUrl = url.GetLeftPart(UriPartial.Path) + "?" + query;
result: http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=10
for example, using query["fid"] = "%".ToString(); you correctly generate http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=%25
demo: https://dotnetfiddle.net/zZ9Y1h
String.Format is one way of replacing token values in a string, if that's what you want. In the example below, the {0} is a token, and String.Format takes the fixedString and replaces the token with the value of myDecimal.
string fixedString = "infinity.world.uk/Members/namelist.aspx?ID=-1&fid={0}";
decimal myDecimal = 1.5d;
string myResultString = string.Format(fixedString, myDecimal.ToString());
I have a string "-4.00 %" which I need to convert to a decimal so that I can declare it as a variable and use it later. The string itself is found in string[] rows. My code is as follows:
foreach (string[] row in rows)
{
string row1 = row[0].ToString();
Match rownum = Regex.Match(row1.ToString(), #"\-?\d+\.+?\d+[^%]");
string act = Convert.ToString(rownum); //wouldn't convert match to decimal
decimal actual = Convert.ToDecimal(act);
textBox1.Text = (actual.ToString());
}
This results in "Input string was not in a correct format." Any ideas?
Thanks.
I see two things happening here that could contribute.
You are treating the Regex Match as though you expect it to be a string, but what a Match retrieves is a MatchGroup.
Rather than converting rownum to a string, you need to lookat rownum.Groups[0].
Secondly, you have no parenthesised match to capture. #"(\-?\d+\.+?\d+)%" will create a capture group from the whole lot. This may not matter, I don't know how C# behaves in this circumstance exactly, but if you start stretching your regexes you will want to use bracketed capture groups so you might as well start as you want to go on.
Here's a modified version of your code that changes the regex to use a capturing group and explicitly look for a %. As a consequence, this also simplifies the parsing to decimal (no longer need an intermediary string):
EDIT : check rownum.Success as per executor's suggestion in comments
string[] rows = new [] {"abc -4.01%", "def 6.45%", "monkey" };
foreach (string row in rows)
{
//regex captures number but not %
Match rownum = Regex.Match(row.ToString(), #"(\-?\d+\.+?\d+)%");
//check for match
if(!rownum.Success) continue;
//get value of first (and only) capture
string capture = rownum.Groups[1].Value;
//convert to decimal
decimal actual = decimal.Parse(capture);
//TODO: do something with actual
}
If you're going to use the Match class to handle this, then you have to access the Match.Groups property to get the collection of matches. This class assumes that more than one occurrence appears. If you can guarantee that you'll always get 1 and only 1 you could get it with:
string act = rownum.Groups[0];
Otherwise you'll need to parse through it as in the MSDN documentation.
I need to strip out any "&id=SomeValue" from a Url.PathAndQuery. Where SomeValue could be an int or a string. And it may or may not be followed by another ampersand.
So it could be
somepage.aspx?cat=22&id=SomeId¶m2=4
or
somepage.aspx?cat=tect&id=450
I want to be left with
somepage.aspx?cat=22¶m2=4
or
somepage.aspx?cat=tect
Just going off the top of my head...
string url = "somepage.aspx?cat=22&id=SomeId¶m2=4";
Regex regex = new Regex("([\?\&])id=[^\?\&]+");
url = regex.replace(url, "\1");
System.Diagnostics.Debug.WriteLine("url = " + url);
Update 2010-03-05 11:12 PM PST
I've been shamed by a comment into actually testing my code. What are you, my QA department? Here's a working example using MSTest.
Regex regex = new Regex(#"([\?\&])id=[^\&]+[\&]?");
[TestMethod]
public void RegexReplacesParameterInMiddle()
{
string url = "somepage.aspx?cat=22&id=SomeId¶m2=4";
url = regex.Replace(url, "$1");
Assert.AreEqual("somepage.aspx?cat=22¶m2=4",url);
}
[TestMethod]
public void RegexReplacesParameterInFront()
{
string url = "somepage.aspx?id=SomeId&cat=22¶m2=4";
url = regex.Replace(url, "$1");
Assert.AreEqual("somepage.aspx?cat=22¶m2=4", url);
}
[TestMethod]
public void RegexReplacesParameterAtEnd()
{
string url = "somepage.aspx?cat=22¶m2=4&id=SomeId";
url = regex.Replace(url, "$1");
Assert.AreEqual("somepage.aspx?cat=22¶m2=4&", url);
}
[TestMethod]
public void RegexReplacesSoleParameter()
{
string url = "somepage.aspx?id=SomeId";
url = regex.Replace(url, "$1");
Assert.AreEqual("somepage.aspx?", url);
}
public void RegexIgnoresMissingParameter()
{
string url = "somepage.aspx?foo=bar&blet=monkey";
url = regex.Replace(url, "$1");
Assert.AreEqual("somepage.aspx?foo=bar&blet=monkey", url);
}
The regex, interpreted, says:
Look for a "?" or an "&" character (and store it as a backreference)
followed by "id="
followed by one or more non-"&" characters.
optionally followed by another "&"
Then replace that expression with the backreference, so you don't lose your initial ?/&.
note -- as you can see from the tests, this emits a trailing ? or & when the replaced parameter is the only one or the last one, respectively. You could use string methods to get rid of that, though if somebody knows how to keep them out of the result using only regular expressions it would be excellent to see.
If bad things could happen (e.g., security-wise) if an "id=" parameter were missed by the regular expression, then you also need to worry that the query string might contain a hexadecimal urlencoded equivalent, which the regular expression will not recognize. For example, "id" is "%69%64". Also consider the effects of different capitalizations of "id" on your program. My opinion in this situtation is that you read the RFCs and build a complete class that can do transformations in both directions from a set of name-value pairs to a query strings. System.Uri will not do this. if you are running inside an ASP.NET application, you might investigate if HttpUtility.ParseQueryString is sufficient.
I would first parse the Querystring to Strongly typed values, then I would check using Regex if I needed to.
C# ASP.NET QueryString parser
I have a SQL Server database (service-based) with a table (Contact). Instead of having multiple tables, I decided to have one delimited string called Emails. So how could I use a Regex and a delimiter to add on to the string.
First of all, you should consider to change your decision to have delimited values instead of an extra table. It may seem simpler at first, but as you have already noticed, it quickly gets painful to work with.
That said, there are some different ways to handle delimited values, but using a regular expression is hardly one of them.
For example:
if (value.Length == 0) {
value = email;
} else {
value = value + delimiter + email;
}
Or:
List<string> emails = new List(value.Split(new String[]{ delimiter }));
emails.Add(email);
value = String.Join(delimiter, emails.ToArray());