RegEx for an IP Address - c#

I try to extract the value (IP Address) of the wan_ip with this sourcecode:
Whats wrong?! I´m sure that the RegEx pattern is correct.
String input = #"var product_pic_fn=;var firmware_ver='20.02.024';var wan_ip='92.75.120.206';if (parent.location.href != window.location.href)";
Regex ip = new Regex(#"[\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
string[] result = ip.Split(input);
foreach (string bla in result)
{
Console.WriteLine(bla);
}
Console.Read();

The [ shouldn't be at the start of your pattern. Also, you probably want to use Matches(...).
Try:
String input = #"var product_pic_fn=;var firmware_ver='20.02.024';var wan_ip='92.75.120.206';if (parent.location.href != window.location.href)";
Regex ip = new Regex(#"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
MatchCollection result = ip.Matches(input);
Console.WriteLine(result[0]);

Very old post, you should use the accepted solution, but consider using the right RegEx for an IPV4 adress :
((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
If you want to avoid special caracters after or before you can use :
^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$

Try this:
Match match = Regex.Match(input, #"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}");
if (match.Success)
{
Console.WriteLine(match.Value);
}

If you just want check correct IP use IPAddress.TryParse
using System.Net;
bool isIP(string host)
{
IPAddress ip;
return IPAddress.TryParse(host, out ip);
}

I know this post isn't new, but, I've tried several of the proposed solutions and none of them work quite as well as one I found thanks to a link provided by Justin Jones. They have quite a few for IP Address but this is the top of the list and using LinqPad (I LOVE LinqPad) most tests I've thrown at it work extremely well. I recommend utilizing this one rather than any of the previous provided expressions:
^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$
Give that a shot in LinqPad with the following:
// \b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b 355.168.0.1 = 355.168.0.1 (Not Correct)
// ((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) 355.168.0.1 = 55.168.0.1 (Not correct)
// \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} 355.168.0.1 = 355.168.0.1 (Not Correct)
// ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ 355.168.0.1 = 355.168.0.1 (Not Correct)
// ^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$ 355.168.0.1 = 355.168.0.1 (Not Correct)
// ^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$ 355.168.0.1 = No Match (Correct)
Match match = Regex.Match("355.168.0.1", #"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$");
if (match.Success) {
Console.WriteLine(match.Value);
}
else {
Console.WriteLine("No match.");
}
With the new RegEx this is not valid which is correct: 355.168.0.1 = No Match which is correct as noted in the comments.
I welcome any tweaks to this as I'm working on a tool that is making use of the expression and am always looking for better ways of doing this.
UPDATE: I've created a .NET Fiddle project to provide a working example of this expression along with a list of IP Addresses that test various values. Feel free to tinker with it and try various values to exercise this expression and provide any input if you find a case where the expression fails. https://dotnetfiddle.net/JoBXdI
UPDATE 2: Better yet refer to this post: Another related question.
Thanks and I hope this helps!

Regex.IsMatch(input, #"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$")

Avoid using /b - it allows characters before or after the IP
For example ...198.192.168.12... was valid.
Use ^ and $ instead if you can split the input into chunks that would isolate the IP address.
Regex regexIP = new Regex(#"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$");
if (regexIP.Match(textBoxIP.Text).Success){
String myIP = textBoxIP.Text;
}
Note above will not validate the digits, as pointed out 172.316.254.1 was true. This only checks correct formatting.
UPDATE: To validate FORMATTING and VALUES you could use
Regex regexIP = new Regex(#"^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$");
if (regexIP.Match(textBoxIP.Text).Success){
String myIP = textBoxIP.Text;
}
(note using ([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]) for each numeric value)
Credit: https://stackoverflow.com/a/10682785/4480932

I think you need to get rid of the [ - is that a stray character or what?
Regex(#"[\b\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}\b")

Regex(#"\A\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}\z") try with this

I took this pattern from UrlAttribute.cs. at DataAnnotations namespace. As you may see, I took just a piece of the original pattern from source.
Regex.IsMatch(input, #"^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-
9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-
9]\d|1\d\d|2[0-4]\d|25[0-5])$");

(\d{1,3}\.){3}(\d{1,3})[^\d\.]
Check this. It should work perfectly

Another variant, depending on how you want to treat padding (e.g. a.b.c.00 is considered invalid format):
^(?25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]|[1-9]{1}|0{1})(.(?25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]|[1-9]{1}|0{1})){3}$

In Python:
>>> ip_regex = r'^{0}\.{0}\.{0}\.{0}$'.format(r'(25[0-5]|(?:2[0-4]|1\d|[1-9])?\d)')
>>> match(ip_regex, '10.11.12.13')
<re.Match object; span=(0, 11), match='10.11.12.13'>
>>> _.groups()
('10', '11', '12', '13')
>>>

Related

Parsing Email To Header

Ok so I am currently facing a few difficulties with my email parser
When I started, most of the emails I tested with was something like the following
"name#domain.co.za, othername#domain.co.za" this I can easilly split by the comma, but I get the following cases that doesn't work
1) "\"Surname, Name, Company Country\" <name.surname#domain.co.za>"
With that I tried the following
Regex.Split(Headers["to"] ?? "", "(?<=#\\S*)\\s+");
But that doesn't remove the comma then so I am using .Trim(',') to remove the trailing comma then some cases work
Example that works
"name#domain.co.za, othername#domain.co.za"
For example the following doesn't work
2) "\"Name Surname <name#domain.co.za>\" <name#domain.co.za>"
I also tried to use Regex.Split(Headers["to"] ?? "", ",(?:^|,)(\"(?:[^\"]+|\"\")*\"|[^,]*)");
But it fails in a situation like the following
"\"Name Surname\" <Name#domain.co.za>, \"Name Surname\" <Othername#domain.co.za>"
Now using a new Regex (?:""([^""]+)"")?\s*<?\b(\S+#\S+\.\S+)\b it is quite close, using the following exaple I get the following output
Input: "\"Donald Jansen\" <Donald#peachss.co.za>, \"Donald Jansen\" <djhabana#gmail.com>"
Output
"\"Donald Jansen\" <Donald#peachss.co.za
\"Donald Jansen\" <djhabana#gmail.com
So it ignored the trailing >, I fixed this by adding >? to the regex and I also found a new scenario that is not working, so the regex is now (?:"([^"]+)")?\s*<?\b(\S+#\S+\.\S+)\b>?
"name <name#xxx.co.za>, name name <name#xxx.co.za>, name <name#xxx.co.za>, \"'name'\" <name#xxx.com>"
The output now is
<name#xxx.co.za> << not correct name is needed
<name#xxx.co.za> << not correct name is needed
<name#xxx.co.za> << not correct name is needed
\"'name'\" <name#xxx.com>" << this is correct
This might do the trick to find all valid emails in the string.
Regex emailRegex = new Regex(#"\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase);
MatchCollection emailMatches = emailRegex.Matches(data);
foreach (Match emailMatch in emailMatches)
{
Console.WriteLine(emailMatch.Value);
}
You can use the 'Email Regex' from emailregex.com
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
Thanks to the help that #MohitShrivastava and #WiktorStribiżew I managed to build my own regex using a combination of their regex that they provided, it is probably not optimized and a bit ugly but it is working as I expect it to
((\w+[ ])|\"(.*?)\"+[ ])+(<?\b(\S+#\S+\.\S+)\b>)|(\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*)
Sample code
var emailRegex = new Regex(#"((\w+[ ])|\""(.*?)\""+[ ])+(<?\b(\S+#\S+\.\S+)\b>)|(\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*)", RegexOptions.IgnoreCase);
var emailMatches = emailRegex.Matches(Headers["to"]);
foreach (Match emailMatch in emailMatches)
{
try
{
To.Add(new MailAddress(emailMatch.Value));
}
catch (Exception ex)
{
}
}

Parse Line and Break it into Variables

I have a text file that contain only the FULL version number of an application that I need to extract and then parse it into separate Variables.
For example lets say the version.cs contains 19.1.354.6
Code I'm using does not seem to be working:
char[] delimiter = { '.' };
string currentVersion = System.IO.File.ReadAllText(#"C:\Applicaion\version.cs");
string[] partsVersion;
partsVersion = currentVersion.Split(delimiter);
string majorVersion = partsVersion[0];
string minorVersion = partsVersion[1];
string buildVersion = partsVersion[2];
string revisVersion = partsVersion[3];
Altough your problem is with the file, most likely it contains other text than a version, why dont you use Version class which is absolutely for this kind of tasks.
var version = new Version("19.1.354.6");
var major = version.Major; // etc..
What you have works fine with the correct input, so I would suggest making sure there is nothing else in the file you're reading.
In the future, please provide error information, since we can't usually tell exactly what you expect to happen, only what we know should happen.
In light of that, I would also suggest looking into using Regex for parsing in the future. In my opinion, it provides a much more flexible solution for your needs. Here's an example of regex to use:
var regex = new Regex(#"([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9])");
var match = regex.Match("19.1.354.6");
if (match.Success)
{
Console.WriteLine("Match[1]: "+match.Groups[1].Value);
Console.WriteLine("Match[2]: "+match.Groups[2].Value);
Console.WriteLine("Match[3]: "+match.Groups[3].Value);
Console.WriteLine("Match[4]: "+match.Groups[4].Value);
}
else
{
Console.WriteLine("No match found");
}
which outputs the following:
// Match[1]: 19
// Match[2]: 1
// Match[3]: 354
// Match[4]: 6

Regex matching dynamic words within an html string

I have an html string to work with as follows:
string html = new MvcHtmlString(item.html.ToString()).ToHtmlString();
There are two different types of text I need to match although very similar. I need the initial ^^ removed and the closing |^^ removed. Then if there are multiple clients I need the ^ separating clients changed to a comma(,).
^^Client One- This text is pretty meaningless for this task, but it will exist in the real document.|^^
^^Client One^Client Two^Client Three- This text is pretty meaningless for this task, but it will exist in the real document.|^^
I need to be able to match each client and make it bold.
Client One- This text is pretty meaningless for this task, but it will exist in the real document.
Client One, Client Two, Client Three- This text is pretty meaningless for this task, but it will exist in the real document.
A nice stack over flow user provided the following but I could not get it to work or find any matches when I tested it on an online regex tester.
const string pattern = #"\^\^(?<clients>[^-]+)(?<text>-.*)\|\^\^";
var result = Regex.Replace(html, pattern,
m =>
{
var clientlist = m.Groups["clients"].Value;
var newClients = string.Join(",", clientlist.Split('^').Select(s => string.Format("<strong>{0}</strong>", s)));
return newClients + m.Groups["text"];
});
I am very new to regex so any help is appreciated.
I'm new to C# so forgive me if I make rookie mistakes :)
const string pattern = #"\^\^([^-]+)(-[^|]+)\|\^\^";
var temp = Regex.Replace(html, pattern, "<strong>$1</strong>$2");
var result = Regex.Replace(temp, #"\^", "</strong>, <strong>");
I'm using $1 even though MSDN is vague about using that syntax to reference subgroups.
Edit: if it's possible that the text after - contains a ^ you can do this:
var result = Regex.Replace(temp, #"\^(?=.*-)", "</strong>, <strong>");

C# - Searching strings

I can't seem to find a good solution to this issue. I've got an array of strings that are fed in from a report that I recieve about lost or stolen equipment. I've been using the string.IndexOf function through the rest of the form and it works quite well. This issue is with the field that says if the device was lost or stolen.
Example:
"Lost or Stolen? Lost"
"Lost or Stolen? Stolen"
I need to be able to read this but when I do string.IndexOf(#"Lost") it will always return lost because it's in the question.
Unfortunately I'm not able to change the form itself in any way and due to the nature of how it's submited I can't just write code the knocks the first 15 or so characters off the string because that may be too few in some cases.
I would really like something in C# that would allow me to continue to search a string after the first result is found so that the logic would look like:
string my_string = "Lost or Stolen? Stolen";
searchFor(#"Stolen" in my_string)
{
Found Stolen;
Does it have "or " infront of it? yes;
ignore and keep searching;
Found Stolen again;
return "Equipment stolen";
}
Couple of options here. You could look for the last index of a space and take the rest of the string:
string input = "Lost or Stolen? Stolen";
int lastSpaceIndex = input.LastIndexOf(' ');
string result = input.Substring(lastSpaceIndex + 1);
Console.WriteLine(result);
Or you could split it and take the last word:
string input = "Lost or Stolen? Lost";
string result = input.Split(' ').Last();
Console.WriteLine(result);
Regex is also an option, but overkill given the simpler solutions above. A nice shortcut that fits this scenario is to use the RegexOptions.RightToLeft option to get the first match starting from the right:
string result = Regex.Match(input, #"\w+", RegexOptions.RightToLeft).Value;
If I understand your requirement, you're looking for an instance of Lost or Stolen after a ?:
var q = myString.IndexOf("?");
var lost = q >= 0 && myString.IndexOf("Lost", q) > 0;
var stolen = q >= 0 && myString.IndexOf("Stolen", q) > 0;
// or
var lost = myString.LastIndexOf("Lost") > myString.IndexOf("?");
var stolen = myString.LastIndexOf("Stolen") > myString.IndexOf("?");
// don't forget
var neither = !lost && !stolen;
You can look for the string 'Lost' and if it occurs twice, then you can confirm it is 'Lost'.
Its possible in this case that you could use index of on a substring knowing that it is always going to say lost or stolen first
so you parse out the lost or stolen, then like for you keyword to match the remaining string.
something like:
int questionIndex = inputValue.indexOf("?");
string toMatch = inputValue.Substring(questionIndex);
if(toMatch == "Lost")
If it works for your use case, it might be easier to use .EndsWith().
bool lost = my_string.EndsWith("Lost");

C# Regex help getting multiple values

Needing a bit help getting multiple values from a string using Regex. I am fine getting single values from the string but not multiple.
I have this string:
[message:USERPIN]Message to send to the user
I need to extract both the USERPIN and the message. I know how to get the pin:
Match sendMessage = Regex.Match(message, "\\[message:[A-Z1-9]{5}\\]");
Just not sure how to get both of the values at the same time.
Thanks for any help.
Use Named Groups for easy access:
Match sendMessage = Regex.Match(message,
#"\[message:(?<userpin>[A-Z1-9]{5})\](?<message>.+)");
string pin = sendMessage.Groups["userpin"].Value;
string message = sendMessage.Groups["message"].Value;
var match = Regex.Match(message, #"\[message:([^\]]+)\](.*)");
After - inspect the match.Groups with debugger - there you have to see 2 strings that you expect.
You need to use numbered groups.
Match sendMessage = Regex.Match(message, "\\[message:([A-Z1-9]{5})(.*)\\]");
string firstMatch = sendMessage.Groups[1].Value;
string secondMatch = sendMessage.Groups[2].Value;

Categories

Resources