I have List that I want to display in my form. But first, I want to move all the non relevant part. This is my List:
===================================================================
Protocol Hierarchy Statistics
Filter:
eth frames:8753 bytes:6185473
ip frames:8753 bytes:6185473
tcp frames:8661 bytes:6166313
http frames:1230 bytes:792126
data-text-lines frames:114 bytes:82636
tcp.segments frames:56 bytes:41270
image-gif frames:174 bytes:109968
tcp.segments frames:57 bytes:37479
image-jfif frames:195 bytes:154407
tcp.segments frames:185 bytes:142340
png frames:35 bytes:30521
tcp.segments frames:20 bytes:15770
media frames:39 bytes:32514
tcp.segments frames:32 bytes:24755
tcp.segments frames:6 bytes:1801
xml frames:5 bytes:3061
tcp.segments frames:1 bytes:960
ssl frames:20 bytes:14610
udp frames:92 bytes:19160
dns frames:92 bytes:19160
===================================================================
I want to display the first column (protocol type) and in the second column only the part after "frames:" without bytes:xxxx
Probably using Regex, something along the lines of:
Regex rgx = new Regex(#"^(?<protocol>[ a-zA-Z0-9\-\.]*)frames:(?<frameCount>[0-9]).*$");
foreach (Match match in rgx.Matches(myListOfProtocolsAsAString))
{
if(match.Success)
{
string protocol = match.Groups[1].Value;
int byteCount = Int32.Parse(match.Groups[2].Value);
}
}
Then you can access the matching groups (protocol & framecount) on the Match instance.
Using the ever popular Linq to Objects
var lines = new string[]
{
"eth frames:8753 bytes:6185473",
"ip frames:8753 bytes:6185473"
};
var values = lines.Select(
line=>line.Split(new string[]{"frames:", "bytes:"}, StringSplitOptions.None))
.Select (items => new {Name=items[0].Trim(), Value=items[1].Trim()});
Related
I have C# code to update the ip address for an NSG rule:
var nsg = azure.NetworkSecurityGroups.GetByResourceGroup("rg", "testnsg");
var nsgrule = nsg.SecurityRules["testrule"];
nsg.Update().UpdateRule("testrule").ToAddress(IpAddress1);
nsg.Update().UpdateRule("testrule").ToAddress(IpAddress2);
nsg.Update().Apply();
The second ip address overwrites the first one.
I have also tried this:
nsg.Update().UpdateRule("testrule").ToAddress(IpAddress1 + ',' + IpAddress2);
But that gives an error that only one ip address is allowed.
Is there a way in C# to specify multiple ip addresses for the nsg rule?
This works:
var nsg = azure.NetworkSecurityGroups.GetByResourceGroup("rg", "testnsg");
var nsgrule = nsg.SecurityRules["testrule"];
List<string> ips = new List<string>();
ips.Add(IpAddress1);
ips.Add(IpAddress2);
nsgrule.Inner.DestinationAddressPrefixes = ips;
nsg.Update().Apply();
I have string coming in this format as shown bellow:
"mark345345#test.com;rtereter#something.com;terst#gmail.com;fault#mail"
What would be the most efficient way to validate each of these above and fail if it is not valid e-mail?
you can use EmailAddressAttribute class of System.ComponentModel.DataAnnotations namespace for validating the email address. Before that you need to split up individual mails and check whether it is valid or not. the following code will help you to collect the valid mails and invalid mails seperately.
List<string> inputMails = "mark345345#test.com;rtereter#something.com;terst#gmail.com;fault#mail".Split(';').ToList();
List<string> validMails = new List<string>();
List<string> inValidMails = new List<string>();
var validator = new EmailAddressAttribute();
foreach (var mail in inputMails)
{
if (validator.IsValid(mail))
{
validMails.Add(mail);
}
else
{
inValidMails.Add(mail);
}
}
You can use Regex or you might split the string by ';' and try to create a System.Net.Mail.MailAddress instance for each and every address. FormatException will occur if address is not in a recognized format.
If you're sure, that all e-mails are semi colon separated, you can split it and make a list of all. The best way for me to validate each e-mail is to use a regex pattern. I've used this one:
var emailPattern = #"(?=^.{1,64}#)^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?=.{1,255}$|.{1,255};)(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])(;(?=.{1,64}#)[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?=.{1,255}$|.{1,255};)(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9]))*$";
var incomingString = "mark345345#test.com;rtereter#something.com;terst#gmail.com;fault#mail";
var emails = incomingString.Split(';').ToList();
foreach (var email in emails)
{
if (new Regex(emailPattern).IsMatch(email))
{
// your logic here
}
}
Since .Net has out of the box ways to validate an email id, I would not use a regex and rely upon .Net. e.g the EmailAddressAttribute from System.ComponentModel.DataAnnotations.
A clean way to use it would be something like:
var emailAddressAttribute = new EmailAddressAttribute();
var groups = yourEmailsString.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.GroupBy(emailAddressAttribute.IsValid);
This will give you 2 groups, the one with the Key == true will be valid email ids
var validEmailIds = groups.Where(group => group.Key)
.SelectMany(group => group);
the one with Key == false will be invalid email ids
var invalidEmailIds = groups.Where(group => !group.Key)
.SelectMany(group => group);
You could also run up a for loop after grouping, according to your needs..
I'm writing a function that will parse a file similar to an XML file from a legacy system.
....
<prod pid="5" cat='gov'>bla bla</prod>
.....
<prod cat='chi'>etc etc</prod>
....
.....
I currently have this code:
buf = Regex.Replace(entry, "<prod(?:.*?)>(.*?)</prod>", "<span class='prod'>$1</span>");
Which was working fine until it was decided that we also wanted to show the categories.
The problem is, categories are optional and I need to run the category abbreviation through a SQL query to retrieve the category's full name.
eg:
SELECT * FROM cats WHERE abbr='gov'
The final output should be:
<span class='prod'>bla bla</span><span class='cat'>Government</span>
Any idea on how I could do this?
Note1: The function is done already (except this part) and working fine.
Note2: Cannot use XML libraries, regex has to be used
Regex.Replace has an overload that takes a MatchEvaluator, which is basically a Func<Match, string>. So, you can dynamically generate a replacement string.
buf = Regex.Replace(entry, #"<prod(?<attr>.*?)>(?<text>.*?)</prod>", match => {
var attrText = match.Groups["attr"].Value;
var text = match.Groups["text"].Value;
// Now, parse your attributes
var attributes = Regex.Matches(#"(?<name>\w+)\s*=\s*(['""])(?<value>.*?)\1")
.Cast<Match>()
.ToDictionary(
m => m.Groups["name"].Value,
m => m.Groups["value"].Value);
string category;
if (attributes.TryGetValue("cat", out category))
{
// Your SQL here etc...
var label = GetLabelForCategory(category)
return String.Format("<span class='prod'>{0}</span><span class='cat'>{1}</span>", WebUtility.HtmlEncode(text), WebUtility.HtmlEncode(label));
}
// Generate the result string
return String.Format("<span class='prod'>{0}</span>", WebUtility.HtmlEncode(text));
});
This should get you started.
What I need:
I have a string like this:
Bike’s: http://website.net/bikeurl Toys: http://website.net/rc-cars
Calendar: http://website.net/schedule
I want to match the word I specify and the first URL after it. So if i specify the word as "Bike" i should get:
Bike’s: http://website.net/bikeurl
Or if possible only the url of the Bike word:
http://website.net/bikeurl
Or if I specify Toys I should get:
Toys: http://website.net/rc-cars
or if possible
http://website.net/rc-cars
What I am using:
I am using this regex:
(Bike)(.*)((https?|ftp):/?/?)(?:(.*?)(?::(.*?)|)#)?([^:/\s]+)(:([^/]*))?(((?:/\w+)*)/)([-\w.]+[^#?\s]*)?(\?([^#]*))?(#(.*))?
Result:
It is matching:
Bike’s: http://website.net/bikeurl Toys: http://website.net/rc-cars
I only want:
Bike’s: http://website.net/bikeurl
I am not a regex expert, I tried using {n} {n,} but it either didn't match anything or matches the same
I am using .NET C# so I am testing here http://regexhero.net/tester/
Here is another approach:
Bike(.*?):\s\S*
and here is an example how to get the corresponding URL-candidate only:
var inputString = "Bike’s: http://website.net/bikeurl Toys: http://website.net/rc-cars Calendar: http://website.net/schedule";
var word = "Bike";
var url = new Regex( word + #"(.*?):\s(?<URL>\S*)" )
.Match( inputString )
.Result( "${URL}" );
If you really need to make sure it's an url look at this:
Validate urls with Regex
Regex to check a valid Url
Here's another solution. I would separate the Bike's, Toys and Calendar in a dictionary and put the url as a value then when needed call it.
Dictionary<string, string> myDic = new Dictionary<string, string>()
{
{ "Bike’s:", "http://website.net/bikeurl" },
{ "Toys:", "http://website.net/rc-cars" },
{ "Calendar:", "http://website.net/schedule" }
};
foreach (KeyValuePair<string, string> item in myDic)
{
if (item.Key.Equals("Bike's"))
{
//do something
}
}
Hope one of my ideas helps you.
If I understood your problem correctly. You need a generic regex that will select a url based on a word. Here is one that would select the url with bike in it:
(.(?<!\s))*\/\/((?!\s).)*bike((?!\s).)*
If you replace bike with any other word. It would select the respective URL's.
EDIT 1:
Based on your edit, here is one that would select based on the word preceding the URL:
(TOKEN((?!\s).)*\s+)((?!\s).)*
It would select the word + the URL eg.
(Bike((?!\s).)*\s+)((?!\s).)* would select Bike’s: http://website.net/bikeurl
(Toy((?!\s).)*\s+)((?!\s).)* would select Toys: http://website.net/rc-cars
(Calendar((?!\s).)*\s+)((?!\s).)* would select Calendar: http://website.net/schedule
If you want to make sure the string contains a URL, you can use this instead:
(TOKEN((?!\s).)*\s+)((?!\s).)*\/\/((?!\s).)*
It will make sure that the 2nd part of the string ie. the one that is supposed to contain a URL has a // in between.
i wanna actuelly sort a list with email addresses by their domain.
Lets say for an example:
var list = new List<string>();
list.Add(a#hotmail.com);
list.Add(b#aon.at);
list.Add(c#gmail.com);
so the result should be:
b#aon.at
c#gmail.com
a#hotmail.com
is that possible without splitting the email addresses ?
Try this:
var sorted = list.OrderBy(x=>new MailAddress(x).Host).ToList();
it will sort your email addresses by mail host
You could use linq for this. However it is absolutely necessary that you split the email address:
list.OrderBy(email => email.Split('#')[1]).ToList();
You can use Regex to get domain of the emails:
var listSorted = list.OrderBy(email => Regex.Match(email, "#.*").Value)
.ToList();
because:
var temp = Regex.Match("a#hotmail.com", "#.*").Value;
tells: take everything after # sign (including # sign) so temp will be #hotmail.com in this case.