I have a string "(zoneId==176)&&((startTime==100)&&(endTime==1200))" from which i want to fetch the value of startTime and endTime in C#. How to do this i am new to c# programming that why i need some clue
That doesn't look like a String but a block of code. Assuming that is the value entered into your code, you could do the following:
var input = "(zoneId==176)&&((startTime==100)&&(endTime==1200))";
var time = input.Split(')');
var start = time.FirstOrDefault(s => s.Contains("startTime")).Split('=')[2];
var end = time.FirstOrDefault(e => e.Contains("endTime")).Split('=')[2];
Your output would be as follows: 100 and 1200
The above implementation works, but shouldn't be used for production purposes for an assortment of reasons. You'll want to focus on:
Substring
Split
Remove
Regular Expressions
These are all essential to learning how to parse data and or any other form of string manipulation. Hopefully this points you in the proper direction.
Another approach would be:
var input = "(zoneId==176)&&((startTime==100)&&(endTime==1200))";
var section = input.Split('=');
foreach(var region in section)
{
var zone = region.Substring(0, region.Length);
var number = zone.Where(d => char.IsDigit(d)).ToArray();
}
Related
Pretty sure we all do string.format and define some string in a specifed format.
I have a string which is always formatted in a way like this:
const string myString = string.Format("pt:{0}-first:{1}", inputString);
To get {0}, I can always check for pt:{ and read till }.
But what is the best/recommended way to extract {0} & {1} from the above variable myString ?
A Regex version of answer, but again, assuming your input doesnt contain '-'
var example = = "pt:hello-first:23";
var str = "pt:(?<First>[^-]+)-first:(?<Second>[^%]+)";
var match = new Regex(str).Match(example);
var first = match.Groups["First"].Value;
var second = match.Groups["Second"].Value;
It might be a good idea that you define what your variable can/cannot contain.
Not sure if this is the best way to do it, but it's the most obvious:
string example = "pt:123-first:456";
var split = example.Split('-');
var pt = split[0].Substring(split[0].IndexOf(':') + 1);
var first = split[1].Substring(split[1].IndexOf(':') + 1);
As Shawn said, if you can guarantee that the variables wont contain either : or - this will be adequate.
I have a string and need to replace some content based on certain substrings appearing in the string. e.g. a sample string might be
(it.FirstField = "fred" AND it.SecondField = True AND it.ThirdField = False AND it.FifthField = True)
and I want to transform it to:
(it.FirstField = "fred" AND it.SecondField = 'Y' AND it.ThirdField = 'N' AND it.FifthField = True)
i.e. if the substring appears in the string, I want to change the True to 'Y' and the False to 'N', but leave any other True/False values intact.
I have an array of substrings to look for:
string[] booleanFields = { "SecondField", "ThirdField", "FourthField" };
I can use something like if (booleanFields.Any(s => inputString.Contains(s))) to find out if the string contains any of the keywords, but what's the best way to perform the replacement?
Thanks.
In the words of clipit - it looks like you are trying to parse SQL, would you like some help with that?
You can try and do this via string manipulation, but you are going to run into problems - think about what would happen if you replaced "fred" with something else, perhaps:
(it.FirstField = "it.SecondField = True" AND it.SecondField = True)
I'm loathed to recommend it (because it's probably quite difficult), but the correct way to do this is to parse the SQL and manipulate the parsed expression - see Parsing SQL code in C# for what looks like an approach that could make this relatively straightfoward.
It's probably not the best answer due to the two very similar lines (one for true/one for false), but this works and is fairly neat for a Regex (with .Dump() ready for LINQPad paste).
It does however assume that you want to replace every ".FieldName = True" within your content (which will include cases where this format is enclosed in quotes as a string value).
void Main()
{
List<string> booleanFields = new List<string> { "SecondField", "ThirdField", "FourthField" };
string s = #"(it.FirstField = ""fred"" AND it.SecondField = True AND it.ThirdField = False AND it.FifthField = True)";
booleanFields.ForEach(bf => s = Regex.Replace(s, String.Format(#"[.]{0}[ ]*=[ ]*True", bf), String.Format(".{0} = 'Y'", bf)));
booleanFields.ForEach(bf => s = Regex.Replace(s, String.Format(#"[.]{0}[ ]*=[ ]*False", bf), String.Format(".{0} = 'N'", bf)));
s.Dump();
}
I am looking at http://code.google.com/p/google-diff-match-patch/ and have downloaded the file. When I look at it is 2 files
DiffMatchPatch.cs
DiffMatchPatchTest.cs
When I try to make a new object of DiffMatchPatch.cs I have to pass in some operation and string text.
http://neil.fraser.name/software/diff_match_patch/svn/trunk/demos/demo_diff.html
In the demo they cross out the words that are different and that is what I am trying to achieve.
I am trying to compare 2 blocks of text on the server side finds the differences and send a email to the user with the file block of text to them like the end result is in the demo that I posted above.
So does anyone have a tutorial on how to use the C# version?
For reference, this is really easy:
var dmp = new diff_match_patch();
var diffs = dmp.diff_main(text1, text2);
var html = dmp.diff_prettyHtml(diffs);
Implementation with current version(2.1.0) would look like this
var dmp = DiffMatchPatchModule.Default;
var diffs = dmp.DiffMain(text1, text2);
var html = dmp.DiffPrettyHtml(diffs);
For anyone who came across this thread because of the title and expected an explanation on how to use the Google Diff-Match-Patch algorithm via the https://github.com/pocketberserker/Diff.Match.Patch library found on NuGet, to create a diff string, so he can send the change somewhere (e.g. via websocket) and restore it at the destination based on the old value and the diff string, that would work like this:
var oldValue = "Test old text.";
var newValue = "Test new text.";
// create diff string
var dmp = DiffMatchPatch.DiffMatchPatchModule.Default;
var diffs = dmp.DiffMain(oldValue, newValue);
var srcDelta = dmp.DiffToDelta(diffs);
// restore from diff
var dmp = DiffMatchPatch.DiffMatchPatchModule.Default;
var dstDelta = dmp.DiffFromDelta(oldValue, srcDelta);
var restoredNewValue = dmp.DiffText2(dstDelta);
I am reading from history, and I want that when i come across a google query, I can extract the query string. I am not using request or httputility since i am simply parsing a string. however, when i come across URLs like this, my program fails to parse it properly:
http://www.google.com.mt/search?client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&channel=s&hl=mt&source=hp&biw=986&bih=663&q=hotmail&meta=&btnG=Fittex+bil-Google
what i was trying to do is get the index of q= and the index of & and take the words in between but in this case the index of & will be smaller than q= and it will give me errors.
any suggestions?
thanks for your answers, all seem good :) p.s. i couldn't use httputility, not I don't want to. when i add a reference to system.web, httputility isn't included! it's only included in an asp.net application. Thanks again
It's not clear why you don't want to use HttpUtility. You could always add a reference to System.Web and use it:
var parsedQuery = HttpUtility.ParseQueryString(input);
Console.WriteLine(parsedQuery["q"]);
If that's not an option then perhaps this approach will help:
var query = input.Split('&')
.Single(s => s.StartsWith("q="))
.Substring(2);
Console.WriteLine(query);
It splits on & and looks for the single split result that begins with "q=" and takes the substring at position 2 to return everything after the = sign. The assumption is that there will be a single match, which seems reasonable for this case, otherwise an exception will be thrown. If that's not the case then replace Single with Where, loop over the results and perform the same substring operation in the loop.
EDIT: to cover the scenario mentioned in the comments this updated version can be used:
int index = input.IndexOf('?');
var query = input.Substring(index + 1)
.Split('&')
.SingleOrDefault(s => s.StartsWith("q="));
if (query != null)
Console.WriteLine(query.Substring(2));
If you don't want to use System.Web.HttpUtility (thus be able to use the client profile), you can still use Mono HttpUtility.cs which is only an independent .cs file that you can embed in your application. Then you can simply use the ParseQueryString method inside the class to parse the query string properly.
here is the solution -
string GetQueryString(string url, string key)
{
string query_string = string.Empty;
var uri = new Uri(url);
var newQueryString = HttpUtility.ParseQueryString(uri.Query);
query_string = newQueryString[key].ToString();
return query_string;
}
Why don't you create a code which returns the string from the q= onwards till the next &?
For example:
string s = historyString.Substring(url.IndexOf("q="));
int newIndex = s.IndexOf("&");
string newString = s.Substring(0, newIndex);
Cheers
Use the tools available:
String UrlStr = "http://www.google.com.mt/search?client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&channel=s&hl=mt&source=hp&biw=986&bih=663&q=hotmail&meta=&btnG=Fittex+bil-Google";
NameValueCollection Items = HttpUtility.ParseQueryString(UrlStr);
String QValue = Items["q"];
If you really need to do the parsing yourself, and are only interested in the value for 'q' then the following would work:
string url = #"http://www.google.com.mt/search?" +
"client=firefoxa&rls=org.mozilla%3Aen-" +
"US%3Aofficial&channel=s&hl=mt&source=hp&" +
"biw=986&bih=663&q=hotmail&meta=&btnG=Fittex+bil-Google";
int question = url.IndexOf("?");
if(question>-1)
{
int qindex = url.IndexOf("q=", question);
if (qindex > -1)
{
int ampersand = url.IndexOf('&', qindex);
string token = null;
if (ampersand > -1)
token = url.Substring(qindex+2, ampersand - qindex - 2);
else
token = url.Substring(qindex+2);
Console.WriteLine(token);
}
}
But do try to look at using a proper URL parser, it will save you a lot of hassle in the future.
(amended this question to include a check for the '?' token, and support 'q' values at the end of the query string (without the '&' at the end) )
And that's why you should use Uri and HttpUtility.ParseQueryString.
HttpUtility is fine for the .Net Framework. However that class is not available for WinRT apps. If you want to get the parameters from a url in a Windows Store App you need to use WwwFromUrlDecoder. You create an object from this class with the query string you want to get the parameters from, the object has an enumerator and supports also lambda expressions.
Here's an example
var stringUrl = "http://localhost/?name=Jonathan&lastName=Morales";
var decoder = new WwwFormUrlDecoder(stringUrl);
//Using GetFirstByName method
string nameValue = decoder.GetFirstByName("name");
//nameValue has "Jonathan"
//Using Lambda Expressions
var parameter = decoder.FirstOrDefault(p => p.Name.Contains("last")); //IWwwFormUrlDecoderEntry variable type
string parameterName = parameter.Name; //lastName
string parameterValue = parameter.Value; //Morales
You can also see http://www.dzhang.com/blog/2012/08/21/parsing-uri-query-strings-in-windows-8-metro-style-apps
Trying to fiddle around with regex here, my first attempt.
Im trying to extract some figures out of content from an XML tag. The content looks like this:
www.blahblah.se/maps.aspx?isAlert=true&lat=51.958855252721&lon=-0.517657021473527
I need to extract the lat and long numerical vales out of each link. They will always be the same amount of characters, and the lon may or may not have a "-" sign.
I thought about doing it like this below (its obviously not right though): (The string in question is in the "link" tag):
var document = XDocument.Load(e.Result);
if (document.Root == null)
return;
var events = from ev in document.Descendants("item1")
select new
{
Title = (ev.Element("title").Value),
Latitude = Regex.xxxxxxx(ev.Element("link").Value, #"lat=(?<Lat>[+-]?\d*\.\d*)", String.Empty),
Longitude = Convert.ToDouble(ev.Element("link").Value),
};
foreach (var ev in events)
{
do stuff
}
Many thanks!
Try this:
Regex.Match(ev.Element("link").Value, #"lat=(?<Lat>[+-]?\d*\.\d*)").Groups[1].Value
Example:
string ev = "www.blahblah.se/maps.aspx?isAlert=true&lat=51.958855252721&lon=-0.517657021473527";
string s = Regex.Match(ev, #"lat=(?<Lat>[+-]?\d*\.\d*)").Groups[1].Value;
Result:
"51.958855252721"
If you have a URL with GET parameters, I would be tempted to find a library that can pull that apart for you, rather than using regexps. There may be edge cases that your regexp doesn't handle, but a library built for the specific purpose would handle (it depends on the set of data that you have to parse and how well-bounded it is, of course).