Array comparison? - regex

I am making a function that takes in an example and an ip address. For ex.
compare('192.168.*','192.168.0.42');
The asterix indicates that the following parts of ip can be anything. The function returns true or false based on if the example and ip is a match. I tried this kind of solution.
var compare = function(example, ip){
var ex = example.split(".");
var ip = ip.split(".");
var t = 0;
for(var i=0; i<4; i++){
if(ex[i] == ip[i] || ex[i] == "*" || typeof ex[i] === 'undefined' && ex[i-1] == "*"){
t++
if(t==4){
return true
}
}else{
return false;
}
}
}
What are the main advantages of using regular expression over this solution? What would be the best regular expression to do this?

How about checking if they are not equal then just return false?
var compare = function(example, ip){
// You should have some basic IP validations here for both example and ip.
var ex = example.split(".");
var ip = ip.split(".");
for(var i=0; i<ex.length; i++){
if(ex[i]=='*')
break;
if(ex[i]!=ip[i])
return false;
}
return true;
}
alert(compare('333.321.*','333.321.345.765'));
alert(compare('333.322.*','333.321.345.765'));
alert(compare('333.321.345.*','333.321.345.765'));

This goes way better with regular expressions. Try this:
function compare(example, ip) {
var regexp = new RegExp('^' + example.replace(/\./g, '\\.').replace(/\*/g, '.*'));
return regexp.test(ip);
}
compare('192.168.*', '192.168.0.42'); // => true
compare('192.167.*', '192.168.0.42'); // => false
What this does is, it translates your pattern to an regular expression. Regular expressions are extremely powerful in matching string. It also covers cases like this:
compare('192.168.*.42', '192.168.1.42'); // => true
compare('192.167.*.42', '192.168.1.43'); // => false

Related

POSTMAN | GET Variable for if - statement

i want to do a if statement in Postman. I have the Environmet Variable: server_state1 & server_state2
These Variables both gets numbers from 0-3.
Now i want to write a Pre-request-Script in an PUT Statement.
The IF Statement sounds like
var server_state1 = postman.GetEnvironmentVariable("state_server1");
var server_state2 = postman.GetEnvironmentVariable("state_server2");
if (server_state1 === 0 && server_state2 === 0){
postman.SetEnvironmentVariable("server_state12", "Everything is fine");
}
But this does not work.
THE ANSWER IS:
var server_state1 = postman.GetEnvironmentVariable("state_server1");
var server_state2 = postman.GetEnvironmentVariable("state_server2");
if (server_state1 === "0" && server_state2 === "0"){
postman.SetEnvironmentVariable("server_state12", "Everything is fine");
}
The functions you are looking for are defined in lowerCamelCase.
Try to use:
postman.getEnvironmentVariable("state_server1")
postman.setEnvironmentVariable("server_state12", "Everything is fine");
Instead of:
postman.GetEnvironmentVariable("state_server1");
postman.SetEnvironmentVariable("server_state12", "Everything is fine");

regex search term in variable

Do you know how I am able to put the search string inside the RegExp?
Let say if my search term is 'Ame', then I can write
v.name.search(new RegExp(/Ame/i)). //It works
var search = $("#search-query").val();
v.name.search(new RegExp('/'+search+'/i' //It doesn't work
However if the value 'Ame' was stored in the var 'search', how do I use the var?
var search = $("#search-query").val();
if($("#search-query").val().length <1){
$scope.hiddenError = true;
return;
}
$.each(json.products, function(i, v) {
if (v.name.search(new RegExp('/'+search+'/i')) != -1) { //doesn't work
$scope.recentGame.push({ label:v.name, value: v.type, link: v.url });
return;
}
});
When you want to build a custom regular expression from a string, you don't include the delimiters / or the options. You use the following form of the function constructor:
var regex = new RegExp(search, "i");
and use that in the search method.

Extract string using regex in stored procedure

I have a regex expression in javascript which works fine.
var re = /^([0-9]?[A-Z]+?)\s*(?:FM)?[FGHJKMNQUVXZ](?:[02]0)?[12]?[0-9]/i;
var str = 'RVBM2016';
var m;
if ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
Now I am trying to reuse the same expression in my stored procedure in postgres. Here is how I am trying it:
select regexp_replace('BLM2016',
E'/^([0-9]?[A-Z]+?)\s*(?:FM)?[FGHJKMNQUVXZ](?:[02]0)?[12]?[0-9]/i', '', 'g')
This should return BL only. For RVBM2016 it should return RVB and so on..
But now it has no effect on the input text. Is there any syntactical mistake?
I was using the wrong method to extract string out of expression. The correct version is as follows if anyone is interested:
select (regexp_matches('BLM2016', '([0-9]?[A-Z]+?)\s*(?:FM)?[FGHJKMNQUVXZ](?:[02]0)?[12]?[0-9]', 'gi'))[1]

Using RegEx to match URL routes

I'm building a PHP Framework for conclusion of my course, and I've stuck on a solution for match some custom routes and standard routes.
My framework's route are similar at routes of Zend Framework 1.
It's match standard routes for
/module/controller/action/param/value/param2/value2/paramn/valuen
The part of URI are optional, and the / route leads to application module, index controller and index action without params and values.
I'm stuck in some custom routes, that I define this way:
/blog/:postname/
/admin/logout/
/blog/posts/:year/:category/
/about/
That routes must match this examples URI requests.
/blog/my-first-post/
/blog/my-first-post/referenced/facebook/
/admin/logout/
/admin/logout/session-id/246753/action
/blog/posts/2013/turism/
/blog/posts/2013/turism/page/2/
But not had to match the standard routes. The custom routes must precede the standard routes.
Some examples of standard routes. Examples:
/
/application/
/application/index/
/application/index/index/
/blog/posts/view/id/3/
/admin/login/
/admin/login/logout (that one are the
/admin/blog/posts/edit/id/3/
/admin/blog/posts/edit/id/3/success/false/
The way I find to do this ellegantily is using RegEx for the matches, but I've trying to learn RegEx for more than one month and don't got it all.
PS: After match the current route, I must to bind the :variable with the related position in the REQUEST_URI.
Thank you for help.
While admittedly tempting, I wouldn't go with regex in this particular case. Even though I usually go that way. A simple loop and match would do, unless your course is setting some restrictions you have to follow.
I put together an example that should get the job done and runs in the console, just to show what i mean.
function get_route($uri){
$routes = [
'blog#show' => 'blog/:postname',
'admin#logout' => 'admin/logout',
'blog#category' => 'blog/posts/:year/:category',
'home#about' => 'about'
];
$params = [];
$uri = preg_replace('/#|\?.+/', '', $uri); // remove hash or query strings
$uri = preg_replace('/(^\/)?(\/$)?/', '', $uri); // trim slashes
$uri = explode('/', $uri);
$action = null;
foreach ($routes as $this_action => $this_route) { // loop through possible routes
$fractions = explode('/', $this_route);
if (sizeof($fractions) !== sizeof($uri)) continue; // did not match length of uri
for ($i=0; $i<sizeof($uri); $i++) { // compare each part of uri to each part of route
if (substr($fractions[$i], 0, 1) !== ':' && $fractions[$i] !== $uri[$i]) break; // not a match and not a param
if ($i === sizeof($uri)-1) { // made it to the last fraction!
$ii = 0;
foreach ($fractions as $fraction) {
if (substr($fraction, 0, 1) == ':') { // it's a param, map it!
$params[substr($fraction,1)] = $uri[$ii];
}
$ii++;
}
return ['action'=>$this_action, 'params'=>$params];
}
}
}
return false;
}
I could reach my needs with this code, a lot of tests has passed.
public function matchCustomRoute($uri)
{
if($uri == '')
{
return null;
}
$customRoutes = $this->getRoutes();
$explodeUri = explode('/', $uri);
$arrayUri = array();
foreach($explodeUri as $uriPart)
{
if($uriPart == '')
{
continue;
}
$arrayUri[] = $uriPart;
}
$countUri = count($arrayUri);
foreach($customRoutes as $key => $value)
{
$explodeRoute = explode('/',$value['route']);
$arrayRoute = array();
foreach($explodeRoute as $routePart)
{
if($routePart == '')
{
continue;
}
$arrayRoute[] = $routePart;
}
$countRoute = count($arrayRoute);
if($countRoute > $countUri)
{
continue;
}
$matches = 0;
for($i = 0 ; $i < $countRoute ; $i++)
{
$match = preg_match('/'.$arrayUri[$i].'/', '/'.$arrayRoute[$i].'/');
if($match == 0)
{
if(substr($arrayRoute[$i], 0, 1) == ':')
{
$value['params'][substr($arrayRoute[$i], 1)] = $arrayUri[$i];
}
else
{
continue;
}
}
$matches++;
}
if($matches == $countRoute)
{
return $value;
}
}
return null;
}
Thank you for help.

.NET ComponentModel.DataAnnotations issue with RegularExpression attribute

I have to validate a string that's supposed to contain an hour number (e.g. 00 to 23).
I hence set an annotation like:
[RegularExpression("[01]?[0-9]|2[0-3]", ErrorMessage = "Error")]
public string JobStartHour {...}
Unfortunately, this regex doesn't match the inputs from 20 to 23, as it's supposed to do (IMHO).
Doesn't this RegularExpression attribute use the plain old Regex.IsMatch ?
Regex.IsMatch("22", "[01]?[0-9]|2[0-3]")
returns true...
Edit: I know, using a string isn't the best idea so as to store a number, nevertheless, this regex issue is annoying.
This pattern will work. I ran into the same thing. It has to do with using parens to correctly establish the groupings. If the RegExAttribute can't figure it out, it seems to just quit at the pipe symbol.
Here's a unit test.
[TestMethod]
public void CheckHours()
{
var pattern = "([0-1][0-9])|(2[0-3])|([0-9])";
int cnt = 0;
var hours = new string[]
{ "1","2","3","4","5","6","7","8","9",
"01","02","03","04","05","06","07","08","09",
"10","11","12","13","14","15","16","17","18","19",
"20","21","22","23" };
var attribute = new RegularExpressionAttribute(pattern);
bool isMatchOk = false;
bool isAttrOk = false;
foreach (var hour in hours)
{
isMatchOk = System.Text.RegularExpressions.Regex.IsMatch(hour, pattern);
isAttrOk = attribute.IsValid(hour);
if (isMatchOk & isAttrOk)
{ cnt += 1; }
else
{ Debug.WriteLine(hour + " / "
+ isMatchOk.ToString() + " / "
+ isAttrOk.ToString()); }
}
Assert.AreEqual(32, cnt);
}
Try this:
[RegularExpression("2[0-3]|[01]?[0-9]", ErrorMessage = "Error")]
public string JobStartHour {...}
Don't know why this regex isn't correctly interpreted, but a solution is to implement a CustomValidation, which is pretty handy.
[CustomValidation(typeof(MyCustomValidation), "Validate24Hour")]
public string JobStartHour {...}
...
public class MyCustomValidation
{
public static ValidationResult Validate24Hour(string candidate)
{
bool isValid = false;
...
if (isValid)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("Error");
}
}
}
You have to group the | to work properly.
I successfully tried, which should be exactly your regex but grouped and limited to start & end:
^([01]?[0-9]|2[0-3])$
Your named Regex.IsMatch line returns true on every expression on my machine.