Regex for address - javascript

With some addresses a building might take up multiple door numbers for example 13 - 15 StreetName.
The "13 - 15" is the part I am focusing on. How would you do a regular expression to pick out this part.
I thought something like [0-9] - [0-9] which works for 1 - 3 but if the address was 12 - 13 [0-9][0-9] - [0-9][0-9] could work but then I want to make sure that something like 13 - 3 wouldnt work as the addresses cannot go backwards and something like 99 - 103 would also work where the numbers are different lengths. Is it really simple and I'm missing something?
I'm still a student and not very good at regular expressions, I just need it for some js I'm doing and have spent far too long getting nowhere.
Thank you.

There's not really a good way to do this since you're effectively trying to parse something that is not a regular language. Referencing something that you've seen before is allowed by several regular expression languages though, but that won't help you in this specific case.
We can easily go for the brute-force solution though :)
https://regex101.com/r/4bRmiL/1
^(\d{3} - \d{3,}|\d{2} - \d{2,}|\d - \d+)$
As you can see though, it still breaks for cases like 5 - 1 which are probably invalid. That's something you need to check outside of the regex.

I don't think this is even possible with regex. I would instead just do something like this:
var addresses = [
"12 - 14 State St.",
"14 - 12 State St.",
];
addresses.forEach(address => console.log(validAddress(address)));
function validAddress(address) {
return !!(address.match(/\d+\s?-\s?\d+/) || []).filter(a => {
var numbers = a.split('-').map(b => b.trim());
return (numbers.length && numbers[0] < numbers[1]);
}).length;
}

Related

How do I reverse an array in JavaScript in 16 characters or less without .reverse()?

I'm trying to solve a challenge on Codewars which requires you to reverse an array in JavaScript, in 16 characters or less. Using .reverse() is not an option.
The maximum number of characters allowed in your code is 28, which includes the function name weirdReverse, so that leaves you with just 16 characters to solve it in. The constraint -
Your code needs to be as short as possible, in fact not longer than 28 characters
Sample input and output -
Input: an array containing data of any types. Ex: [1,2,3,'a','b','c',[]]
Output: [[],'c','b','a',3,2,1]
The starter code given is -
weirdReverse=a=>
My solution (29 characters) is -
weirdReverse=a=>a.sort(()=>1)
which of course fails -
Code length should less or equal to 28 characters.
your code length = 29 - Expected: 'code length <= 28', instead got: 'code length > 28'
I'm not sure what else to truncate here.
Note - I did think about posting this question on CodeGolf SE, but I felt it wouldn't be a good fit there, due to the limited scope.
I'd like to give you a hint, without giving you the answer:
You're close, but you can save characters by not using something you need to add in your code.
By adding the thing you won't use, you can remove ().
Spoiler (answer):
// Note: this only really works for this specific case.
// Never EVER use this in a real-life scenario.
var a = [1,2,3,'a','b','c',[]]
weirdReverse=a=>a.sort(x=>1)
// ^ That's 1 character shorter than ()
console.log(weirdReverse(a))

algorithm to generate short unique human readable id from first and last name

looking for an algorithm that when given a First and a last name, an id is generated such that it consists of purely alphanumeric characters. Also, I would want this to be as short as possible whilst maintaining uniqueness. I was hoping for around 10-12 characters - something that a human could enter.
I have read about suggestions of computing a hash, then simply taking the first n bytes and calling modulus with 36 (the idea is that you have a mapping from 0-35 to the letters a-z 0-9).
Also heard suggestions of maybe truncating and using a higher base to pack more bits into the id.
I guess I could append some encoding of the generation time to the produced id to make it unique but again I need a way for this to be short.
What's your opinion? Are there specific hashing algorithms/truncating methods I should go for? I'll be implementing it in javascript as part of a static html page used as a local webapp.
I am just worried as crypto is hard and I would welcome advice from anyone who thinks they know what they are doing with it.
If it helps the number of ids I expect to make is small - around 4 digits.
One technique would be to just use a combination of the first name and last name, similar to how large companies create email aliases. If you only are creating a few thousand, it wouldn't be hard to work around collisions. These are probably the most human friendly type of id to deal with. For example, Bill Smith would be billsm or something similar.
If you don't want your ids to be easily guessable (though if guessing an id breaks your security model you should probably look into that) then you can go with something like the following (untested javascript pseudocode):
var sequence = 1,
shardId = 1,
epoch = 1357027200000;
function nextId() {
sequence = sequence + 1;
now = Date.now() - epoch;
seqId = sequence % 1023
nextId = now << 15 | shardId << 10 | seqId;
return (nextId).toString(36);
}

Regular expression to validate number greater than 0 and less than 1999

I need a Regular expression to validate number greater than 0 and less than 1999.
I tried the below code but it require LiveValidation and lot of code.
var f8 = new LiveValidation('f8');
f8.add( Validate.Numericality, { minimum: 0, maximum: 1999} );
Thanks
Have you tried something like this:
^[0-1]?[0-9]{0,3}$
How about
([1-9][0-9]{0,2}|1[0-8][0-9]{2}|19[0-8][0-9]|199[0-8])
Just think how much time you are wasting just by looking for an answer to compare a number with regular expression. But I think as a programmer you know that >< symbols are in every language to compare numbers. I recommend you use those.
function is_valid(strNum){
var num = parseInt(strNum);
return (num>0 && num<1999);
}
This code will do what you need and it'll not even waste time
Check out this pattern:
^([0-9]{0,3}|1\d[0-8][9]|1\d{2}[0-8])$
It will allow values between 1 and 1998, inclusive.
I wouldn't do this with regex but try:
/^(?![2-9].{3})\d{1,4}$/
Again, this in unnecesary, but you get the idea.

Javascript regex searching for calendar events

I have a situation where I need to take a sentence and check certain boxes and/or enter numbers into text inputs.
The boxes are things like..
every day
ever week
every month
So I'm not sure if it would be better to use different regex objects to search for the different situations, or if I should try to make 1 big regex object and then switch/case the results.
Here are some examples of what the string can be:
every day
every weekday
every week on sunday, monday, wednesday
every 3 weeks on sunday, friday
every first sunday of every month
day 1 of every 2 months
every january 1
I can do OK when it comes to regex but this is out of league and I'm not sure if I should use different regex objects or try to make a big one. Thanks for any help
It looks like /\w+\s?(\d+?)?\s(\w+)/ takes care of "every week", "every day", "every month", "every year", "every 10 days", etc.
I don't think regular expressions are going to help you much here. They might be able to do some of the really simple matching, but what you're really looking at here is a grammar parsing problem. You might want to read up on languages designed to express abstract grammars, like Extended Backus-Naur Form (EBNF). It sounds intimidating, but it's really not that hard to grasp. Once you're able to describe your grammar in a formal language, suddenly parsing it becomes much easier (at the very least, you have a specification of what kind of inputs are valid). For example, you might have the following EBNF for your problem:
expression = "every" time-unit|time-unit-list|composite-time-unit
time-unit = { ordinal } "day" | "weekday"
ordinal = "first" | "second" | "third" | ...
And so on. This is not a trivial job; parsing an English sentence, even a fairly restrictive one like this can be quite involved. However, it is a well-established and rigorous method.
Once you've got your grammar defined, you can build a parser for it. This is a matter of looking for terminals (like "every") and then matching them to a rule. For example, you might have something like the following (pseudocode):
words = split(/\s*/,lowercase(input))
if( words[0] == "every" ) {
switch( words[1] ) {
case "first":
case "second":
case "third":
...
parseTimeUnit(words);
break;
case "day":
everyDay = true;
break;
...
}
}
Depending on the complexity of your grammar, you might look into automatically generating the parser with something like Yacc.
You've bitten yourself off a hunk of a problem, but it's a rewarding one to work through, so good luck!
Update: I only suggested Yacc because it's among the oldest parser generators I know of. However, there are a million of them, and a lot of them will emit Javascript for you. You can check out Wikipedia's comparison of parser generators for more information.
It seems like what you are trying to do is parse a string into some data structure, and that I believe is not a job for regex (although it could be a part of the solution).

javascript: trying to validate a number that has to be 4 digits to see if x<100 (ie 0100)

i hate asking for help as i would rather figure things for myself, or learn from what others have posted or already asked and solved. as such this is my first post on here!
This is either really really simple and im over complicating things or im going about it the wrong way. ive been searching everywhere for over 2 hours now. im not exactly a noob at js but i am still sort of new,i would say learning, ameteur?? anywho....
what i am trying to do:
so i have a number input box <input type="number" maxlength="4" .../> where a user will enter a 4 digit number (needs to be 4 digits) from 100 to 8000. so obviously 100 to 999 would be 0100 - 0999.
no problem so far, i can just use a string to pass the variable through as 4 digits.
the problem i have is that i need to add certain conditions to validate the input. one condition is bugging me. this is what i have so far:
(var x is already set to the form and number input box)
if (x=="" || isNaN(x) || x.length!== 4 && x< 0100 || x>8000)
{alert(please enter the correct amount!}
else {run rest of function}
so they all work execpt for:x<0100
if the user enters 99 it flags up because it is not 4 digits and if they enter 0099 it accepts it and runs the rest of the function code.
i just need it to alert for any amount from 0001 to 0099.
i found another post, How to make 8 digit number in javascript? , sort of relevant but the guy just wants to output a number padded with zeros. i think one of the solutions (code below) may be of use to me but as i am rather tired, brain frazzled and new i cant solve it:
var i = (100).toPrecision(8).split('.').reverse().join('');
i would start by editing it to:
var i = (x).toPrecision(4).split('.').reverse().join('');
(but would this only work if they typed 99 not 0099...if ya see what i mean)
i think it would be like a reverse of the code (split 0099 to 99.00) , and then the statement would be: if(.... && i<==99 || ....) but idk how to write it in JS...
ok so do ya see how this is messing with me mind, being a semi/quarterly noob and all!!
sorry its not formatted correctly and so long, i havent grasped how to use the code functions...
and thanks for your patience in reading this (if you got this far hehe).
THANKS IN ADVANCE
Slappy-x
The number 0100 will be treated as octal value (which is 64 in decimal).
I think you would do fine by just comparing against strings:
x < "0100" || x > "8000"
Otherwise you have to convert the x into a number and compare it against 100:
+x < 100 || +x > 8000
(actually you don't have to explicitly convert x but it does not hurt either and makes it clearer which data types you are comparing)
Update: And you have to replace && with || as far as I can see.
To check if x is between 0001 and 0099, you can do this
if (x.match(/00([1-9][0-9]|0[1-9])/))
Try a combination of these methods.
You want to check that your number is actually a number first (i.e. doesn't contain letters, etc.). Do this by calling this method to confirm your number is a valid numeric value.
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Once confirmed that you're dealing with a number, you can pad it (if necessary) like this:
function pad(num, size) {
var s = "000" + num;
return s.substr(s.length-size);
}
To work with padded numbers, you actually have to convert the value to a string.

Categories