Is it possible to reuse the logic defined in regex expression twice - javascript

Is it possible to reuse the logic defined in regex expression twice like
I want to match if Day range is defined like
mon-wed or monday-friday.
Here's regex expression used to match one day expression
/\b((mon|tue(s)?|wed(nes)?|thur(s)?|fri|sat(ur)?|sun)(day)?)\b/
It works fine for mon, tuesday etc
but I want to reuse it to with - in the middle

I guess you don't want to just copy and paste the part you want repeated to form something like this:
\b((mon|tue(s)?|wed(nes)?|thur(s)?|fri|sat(ur)?|sun)(day)?)-((mon|tue(s)?|wed(nes)?|thur(s)?|fri|sat(ur)?|sun)(day)?)\b
You can store them as strings, then you concatenate the strings and finally, pass them into new RegEx(...):
var partToBeRepeated = "\\b((mon|tue(s)?|wed(nes)?|thur(s)?|fri|sat(ur)?|sun)(day)?)\\b"
var regex = new RegEx(partToBeRepeated + "-" + partToBeRepeated)

I think this should work
\b((mon|tue(s)?|wed(nes)?|thur(s)?|fri|sat(ur)?|sun)(day)?)\b-\b((mon|tue(s)?|wed(nes)?|thur(s)?|fri|sat(ur)?|sun)(day)?)\b
You can check here for more

Related

JS Regex: how to remove first 2 zero's from "08/08/2017"

I'm new to regex, and have been researching all night how to remove the first 2 zeros from a string like "08/08/2017" (without removing 0 in "2017")
The 5+ regex tutorials I've reviewed do not seem to cover what I need here.
The date could be any sysdate returned from the system. So the regex also needs to work for "12/12/2017"
Here is the best I have come up with:
let sysdate = "08/08/2017"
let todayminuszero = str.replace("0","");
let today = todayminus0.replace("0","");
It works, but obviously it's unprofessional.
From the tutorials, I'm pretty sure I can do something along the lines of this:
str.replace(/\d{2}//g,""),);
This pattern would avoid getting the 3rd zero in str.
Replacement String would have to indicate 8/8/
Not sure how to write this though.
For date manipulation I would use other functions(best date related) but, this should do it, for the case that you stated. If you need other formats or so, I would suggest removing the zeros in an different way, but It all depends on you UseCase.
let sysdate = "08/08/2017";
let todayminuszero = sysdate.replace(/0(?=\d\/)/gi,"");
console.info(todayminuszero);
(?= ... ) is called Lookahead and with this you can see what is there, without replacing it
in this case we are checking for a number and a slash. (?=\d\/)
here some more information, if you want to read about lookahead and more http://www.regular-expressions.info/lookaround.html
A good place to test regex expressions is https://regex101.com/
I always use this for more advance expressions, since it displays all matching groups and so, with a great explaination. Great resource/help, if you are learning or creating difficult Expressions.
Info: as mentioned by Rajesh, the i flag is not needed for this Expression, I just use it out of personal preference. This flag just sets the expression-match to case insensitive.
-- Out of Scope, but may be interesting --
A longer solution without regex could look like this:
let sysdate = "08/08/2017";
let todayminuszero = sysdate.split("/").map(x => parseInt(x)).join("/");
console.info(todayminuszero);
Backside, this solution has many moving parts, the split function to make an array(´"08/08/2017"´ to ´["08", "08", "2017"]´), the map function, with a lambda function => and the parseInt function, to make out of each string item a nice integer (like: "08" to 8, ... ) and at last the join function that creates the final string out of the newly created integer array.
you should use this
let sysdate = "08/08/2017"
let todayminuszero = sysdate.replace(/(^|\/)0/g,"$1");
console.log(todayminuszero);
function stripLeadingZerosDate(dateStr){
return dateStr.split('/').reduce(function(date, datePart){
return date += parseInt(datePart) + '/'
}, '').slice(0, -1);
}
console.log(stripLeadingZerosDate('01/02/2016'));
console.log(stripLeadingZerosDate('2016/02/01'));
look at here
function stripLeadingZerosDate(dateStr){
return dateStr.split('/').reduce(function(date, datePart){
return date += parseInt(datePart) + '/'
}, '').slice(0, -1);
}
console.log(stripLeadingZerosDate('01/02/2016'));// 1/2/2016
console.log(stripLeadingZerosDate('2016/02/01'));// "2016/2/1"
By first 2 zeros, I understand you mean zero before 8 in month and in date.
You can try something like this:
Idea
Create a regex that captures group of number representing date, month and year.
Use this regex to replace values.
Use a function to return processed value.
var sysdate = "08/08/2017"
var numRegex = /(\d)+/g;
var result = sysdate.replace(numRegex, function(match){
return parseInt(match)
});
console.log(result)

Regex for date in format hour.minute dayName day/month

I am trying to verify str with the code below. My final goal is to allow this style of input:
18.30 Saturday_lastMatch 3/10
However, the code I have can't even work for the basic usage (98.5% str will be of this format):
19.30 Friday 15/5
var regex= /[0-9]{2}[\.:][0-9]{2} [A-Z][a-z]{4,7} [0-9]\/[0-9]{2}/;
if(!str.match(regex)) {
//"Bad format, match creation failed!");
}
What am I missing?
There are a number of problems with your regex.
The date & time matching portions at the beginning and end don't allow for 1 or 2 digit numbers as they should.
You may want to consider anchoring the regex at the beginning and end with ^ and $, respectively.
The literal dot in the character class doesn't need to be escaped.
Try this:
var regex= /^[0-9]{1,2}[.:][0-9]{1,2} [A-Z][a-z]{5,8} [0-9]{1,2}\/[0-9]{1,2}$/;
The final part of your regular expression that checks day/month needs to be expanded. It currently only matches #/##, but it should allow ##/# as well. The simplest fix would be to allow either one or two digits on either side (e.g. 12/31)
var regex= /[0-9]{2}[\.:][0-9]{2} [A-Z][a-z]{4,7} [0-9]{1,2}\/[0-9]{1,2}/;

Javascript: Difference in Regex String and Regex [duplicate]

This question already has answers here:
Differences between Javascript regexp literal and constructor
(2 answers)
Closed 7 years ago.
I have to put a given variable into a regular expression. When I do it with hard coded data it works. Here is my code for that
/^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9##$-/:-?{-~!"^_`\[\]])+((?!ccarn).)*$/
This should ( and does ) look for a word (password in this case) that is case sensitive, has at least one capitol and one lowercase letter, and one number or symbol. It cannot, however, contain the word "ccarn" in it. Again when I put this in as my regex all works out. When I try to turn it into a string that gets passed in, it doesn't work. Here is my code for that
var regex = new RegExp('/^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9##$-/:-?{-~!"^_`\[\]])+((?!' + $scope.username + ').)*$/');
I feel like I may just be missing something in translation/transition, but can't seem to get it right. TIA
When you use the new RegExp() constructor to construct a regex from a string, you shouldn't include the leading and trailing / within the string. The /.../ form is only to be used when specifying a regex literal, which isn't what you're doing here.
When you do, say, var r = new RegExp('/foo/'), the regex you're actually getting is equivalent to doing var r = /\/foo\//, which clearly isn't what you want. So your constructor should actually look like this:
var regex = new RegExp('^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9##$-/:-?{-~!"^_`\[\]])+((?!' + $scope.username + ').)*$');
// ↑↑ ↑↑
// no "/" at the locations pointed to above
You probably also need to double your backslashes (since backslashes are escape characters in strings, but not in regex literals). So, [0-9##$-/:-?{-~!"^_`\[\]] needs to become [0-9##$-/:-?{-~!"^_`\\[\\]].
If you look closely the '/' character gets delimited when you give it inside the quotes so essentially the
var regex = new RegExp('/^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9##$-/:-?{-~!"^_`\[\]])+((?!' + $scope.username + ').)*$/');
The regular expression would be like this
/\/^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9##$-\/:-?{-~!"^_`[]])+((?!ccarn).)*$\//
The right way to go is to remove the '/' character from the RegEx and it should work
var regex = new RegExp('/^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9##$-/:-?{-~!"^_`\[\]])+((?!' + $scope.username + ').)*$/');
The output for the above would be
/^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9##$-\/:-?{-~!"^_`[]])+((?!ccarn).)*$/
which is exactly what you need ?
Hope it helps
Please before doing anything else, read a regex tutorial!
Mistakes:
A lookahead is a zero width assertion ( in other words, it's only a test and doesn't match anything ), putting a quantifier for a zero width assertion doesn't make any sense: (?=.*[a-z])+ (it is like repeating something empty, zero or more times. Note that the regex engine will protest if you write something like this.)
When you use the oop syntax to define a pattern (ie:var pattern = new RegExp("...), you don't need to add delimiters. You need to put double backslashes instead simple backslashes.

Look behind replace all occurrences

I want to replace all occurences of .digit with 0.digit.
I'm new to regular expressions but as far as I understand I could use look behind to do this. But JS does not support that, I'd like to know if someone knows a solution.
To show the problem I wrote the following code.
str = "0.11blabla.22bla0.33bla.33"
allow = "\\.\\d*"
str.match(new RegExp(allow,"g"))
[".11", ".22", ".33", ".33"]
deny = "0\\.\\d*"
str.match(new RegExp(deny,"g"))
["0.11", "0.33"]
diffreg= new RegExp("(?!"+deny+")"+allow,"g") // translates to: /(?!0\.\d*)\.\d*/g
str.match(diffreg)
[".11", ".22", ".33", ".33"]
Obviously allow matches all decimal values whereas deny matches all values with a preceding 0. The result should of course be the set difference between the two: [".33", ".33"].
Use a group match.
> str.replace(/([^0])(\.\d)/g, "$10$2");
"0.11blabla0.22bla0.33bla0.33"
I think you are looking for this regex instead
[0]?(\.\d*)
So in your code you will have:
intersectionreg = new RegExp("[0]?("+allow+")","g")
Thanks #richard, edited

Javascript Regex after specific string

I have several Javascript strings (using jQuery). All of them follow the same pattern, starting with 'ajax-', and ending with a name. For instance 'ajax-first', 'ajax-last', 'ajax-email', etc.
How can I make a regex to only grab the string after 'ajax-'?
So instead of 'ajax-email', I want just 'email'.
You don't need RegEx for this. If your prefix is always "ajax-" then you just can do this:
var name = string.substring(5);
Given a comment you made on another user's post, try the following:
var $li = jQuery(this).parents('li').get(0);
var ajaxName = $li.className.match(/(?:^|\s)ajax-(.*?)(?:$|\s)/)[1];
Demo can be found here
Below kept for reference only
var ajaxName = 'ajax-first'.match(/(\w+)$/)[0];
alert(ajaxName);
Use the \w (word) pattern and bind it to the end of the string. This will force a grab of everything past the last hyphen (assuming the value consists of only [upper/lower]case letters, numbers or an underscore).
The non-regex approach could also use the String.split method, coupled with Array.pop.
var parts = 'ajax-first'.split('-');
var ajaxName = parts.pop();
alert(ajaxName);
you can try to replace ajax- with ""
I like the split method #Brad Christie mentions, but I would just do
function getLastPart(str,delimiter) {
return str.split(delimiter)[1];
}
This works if you will always have only two-part strings separated by a hyphen. If you wanted to generalize it for any particular piece of a multiple-hyphenated string, you would need to write a more involved function that included an index, but then you'd have to check for out of bounds errors, etc.

Categories