Below is regex code for getting the number 6 from my tesetstr. How can i extract the string 'months' from teststr using regex ?
var teststr = '6 months';
var num = /(\d+)\s*month/;
var days = teststr.match(num)[1];
console.log(days);
Currently, (\d+) matches one or more digits capturing them into Group 1 (note you are not using the group at all, so, it is redundant).
You seem to want to only match digits before a space + "month". Use the following regex:
var num = /(\d+)\s*month/;
and then access the captured value with
var days = ($('#infra_time_threshold').text()).match(num)[1] * 30;
^^^
Alternatively, you could use a lookahead right after \d+:
var num = /\d+(?=\s*month)/;
and then just use your .match(num)[0] since Group 0 value will be the whole match.
NOTE: You might want to add a null check before accessing the 0th or 1st index of the match object.
Related
I'm working with a string where I need to extract the first n characters up to where numbers begin. What would be the best way to do this as sometimes the string starts with a number: 7EUSA8889er898 I would need to extract 7EUSA But other string examples would be SWFX74849948, I would need to extract SWFX from that string.
Not sure how to do this with regex my limited knowledge is blocking me at this point:
^(\w{4}) that just gets me the first four characters but I don't really have a stopping point as sometimes the string could be somelongstring292894830982 which would require me to get somelongstring
Using \w will match a word character which includes characters and digits and an underscore.
You could match an optional digit [0-9]? from the start of the string ^and then match 1+ times A-Za-z
^[0-9]?[A-Za-z]+
Regex demo
const regex = /^[0-9]?[A-Za-z]+/;
[
"7EUSA8889er898",
"somelongstring292894830982",
"SWFX74849948"
].forEach(s => console.log(s.match(regex)[0]));
Can use this regex code:
(^\d+?[a-zA-Z]+)|(^\d+|[a-zA-Z]+)
I try with exmaple and good worked:
1- somelongstring292894830982 -> somelongstring
2- 7sdfsdf5456 -> 7sdfsdf
3- 875werwer54556 -> 875werwer
If you want to create function where the RegExp is parametrized by n parameter, this would be
function getStr(str,n) {
var pattern = "\\d?\\w{0,"+n+"}";
var reg = new RegExp(pattern);
var result = reg.exec(str);
if(result[0]) return result[0].substr(0,n);
}
There are answers to this but here is another way to do it.
var string1 = '7EUSA8889er898';
var string2 = 'SWFX74849948';
var Extract = function (args) {
var C = args.split(''); // Split string in array
var NI = []; // Store indexes of all numbers
// Loop through list -> if char is a number add its index
C.map(function (I) { return /^\d+$/.test(I) === true ? NI.push(C.indexOf(I)) : ''; });
// Get the items between the first and second occurence of a number
return C.slice(NI[0] === 0 ? NI[0] + 1 : 0, NI[1]).join('');
};
console.log(Extract(string1));
console.log(Extract(string2));
Output
EUSA
SWFX7
Since it's hard to tell what you are trying to match, I'd go with a general regex
^\d?\D+(?=\d)
I am trying to find out a regular expression where I can validate the input and also extract required information from input.
My input contains a simple calculation like addition, subtraction, multiplication and division.
For example: if input is addtion say 7.01+9.05
var input = '7.01+9.05';
var pattern = /^-?\d+\.?\d+[-+*\/]-?\d+\.?\d+$/
var sign;
if (input.match(pattern)) {
var matches = pattern.exec(input);
var left = // logic to extract value 7.01 using matches variable;
var right = // logic to extract value 9.05 using matches variable;
var sing = // logic to extract symbol + using matches variable;
}
I have used the regular expression which I found from this post : Calculator Regular Expression with decimal point and minus sign
Can you please help me how to extract the required data in above code?
In your pattern ^-?\d+\.?\d+[-+*\/]-?\d+\.?\d+$ you want to match an optional dot using \d+\.?\d+ which works but now the minimum number of digits to match is 2 due to matching 2 times 1 or more digits using \d+ so 1+1 would not match.
What you could do if it are only simple calculations, you could use 3 capturing groups and match a digit with an optional decimal part using ?\d+(?:\.\d+)?
Your pattern might look like:
^(-?\d+(?:\.\d+)?)([-+*\/])(-?\d+(?:\.\d+)?)$
Explanation
^ Start of string
(-?\d+(?:\.\d+)?) Capture group 1, match 1+ digits with an optional decimal part
([-+*\/]) Capture group 2, match any of the listed in the character class
(-?\d+(?:\.\d+)?) Capture group 2, match 1+ digits with an optional decimal part
$ End of string
See the regex101 demo
For example
var regex = /^(-?\d+(?:\.\d+)?)([-+*\/])(-?\d+(?:\.\d+)?)$/;
[
"21+22",
"7.01+9.05",
"1-1",
"1*1",
"0*1000000",
"8/4"
].forEach(x => {
var res = x.match(regex);
var left = res[1];
var right = res[2];
var sing = res[3];
console.log(left, right, sing);
});
Sure!
You should define capture groups in your regex expression using () and |. It is important define a flag global to your regex to capture all groups.
There are 3 things you need to capture:
the left number -> ^-?\d+\.?\d+
the sign -> [-+*\/]
the right number -> -?\d+\.?\d+$
You should use | alternation to regex use the capturing groups like a or statement beetwen the groups.
The final regex will be:
var pattern = /(^-?\d+\.?\d+)|([-+*\/])|(-?\d+\.?\d+$)/g
The ouput result will be an array where the first position will be the left number, second position the sign and the third position a right number.
Therefore the rest of your code will looks like that:
if (input.match(pattern)) {
var matches = input.match(pattern); \\ I recommend use input.match here too
var left = matches[0];
var right = matches[2];
var sing = matches[1];
}
You can do that using split()
var input = '7.01+9.05';
var pattern = /^-?\d+\.?\d+[-+*\/]-?\d+\.?\d+$/
if (input.match(pattern)) {
var matches = pattern.exec(input)[0].split(/(\+|-|\*|\/)/);
var left = matches[0];
var right = matches[2];
var sign = matches[1];
console.log(left,sign,right);
}
I have this string:
var s = '/channels/mtb/videos?page=2&per_page=100&fields=uri%2Cname%2Cdescription%2Cduration%2Cwidth%2Cheight%2Cprivacy%2Cpictures.sizes&sort=date&direction=asc&filter=embeddable&filter_embeddable=true'
I want to repace per_page number (in this case 100, but it can be any number from 1-100, maybe more?)
I can select first part of the string with:
var s1 = s.substr(0, s.lastIndexOf('per_page=')+9)
which give me:
/channels/mtb/videos?page=2&per_page=
but how would I select next '&' after that so I can replace number occurrence?
dont assume same order of parameters!
You can use following regex to replace the content you want.
regex:- /per_page=[\d]*/g(this is only for your requirement)
var new_no=12; //change 100 to 12
var x='/channels/mtb/videos?page=2&per_page=100&fields=uri%2Cname%2Cdescription%2Cduration%2Cwidth%2Cheight%2Cprivacy%2Cpictures.sizes&sort=date&direction=asc&filter=embeddable&filter_embeddable=true';
var y=x.replace(/per_page=[\d]*/g,'per_page='+new_no);
console.log(y);
Explanation:-
/per_page=[\d]*/g
/ ----> is for regex pattern(it inform that from next character onward whatever it encounter will be regex pattern)
per_page= ----> try to find 'per_page=' in string
[\d]* ----> match 0 or more digit (it match until non digit encounter)
/g ---->/ to indicate end of regex pattern and 'g' is for global means find in all string(not only first occurrence)
Use replace with a regular expression to find the numbers after the text per_page=. Like this:
s.replace(/per_page=\d+/,"per_page=" + 33)
Replace the 33 with the number you want.
Result:
"/channels/mtb/videos?page=2&per_page=33&fields=uri%2Cname%2Cdescription%2Cduration%2Cwidth%2Cheight%2Cprivacy%2Cpictures.sizes&sort=date&direction=asc&filter=embeddable&filter_embeddable=true"
Start with the index from the lastIndexOf-per_page instead of 0.
Get the index of the first & and create a substr s2 to the end.
Then concat s1 + nr + s2.
I would not use regex, because it is much slower for this simple stuff.
With Array.filter you can do this, where one split the text into key/value pairs, and filter out the one that starts with per_page=.
Stack snippet
var s = '/channels/mtb/videos?page=2&per_page=100&fields=uri%2Cname%2Cdescription%2Cduration%2Cwidth%2Cheight%2Cprivacy%2Cpictures.sizes&sort=date&direction=asc&filter=embeddable&filter_embeddable=true'
var kv_pairs = s.split('&');
var s2 = s.replace((kv_pairs.filter(w => w.startsWith('per_page=')))[0],'per_page=' + 123);
//console.log(s2);
var matches = /(.*\bper_page=)(\d+)(.*)/;
if (matches) {
s = matches[0] + newValue + matches[2];
}
In the below example I need to get the strings which have only 4 and not 44.
var strs = ["3,4,6","4,5,6","1,2,3,4","44,55","55,44","33,44,55"];
var patt = new RegExp(/[,|^\d]*4[,|^\d]*/);
for(i in strs){
var str = strs[i];
var res = patt.test(str);
if(res){
console.log(str);
}else{
console.error(str);
}
}
^(?!.*(\d4|4\d)).*4.*$
(?!.*(\d4|4\d)) it ensure that no string should not contain any digit contain 4 and greater than 10.
.*4.* ensure that string contain at least 1 "4".
Demo
Try
^(?!.*(\d4|4\d).*).*$
It uses a negative look-ahead to assert that there isn't a combination of 4 followed by a digit, or the other way around.
See it here at regex101.
I have a string like
5|10|20|200|300
and i want to get the First Digit Before | and last digit after | that is 5 and 300.
How would I use regex in javascript to return that numbers??
This simplest regex will return the two matches 5 and 300:
^\d+|\d+$
See the matches in the demo.
In JS:
result = yourString.match(/^\d+|\d+$/g);
Explanation
^\d+ matches the beginning of the string and some digits (the 5)
OR |
\d+$ matches some digits and the end of the string
JavaScript only keeps the last capture for (...)+, so you can write
var m = "5|10|20|200|300".match(/(\d+)(\|(\d+))+/);
Then m[1] is "5" and m[3] is "300"
var string = '5|10|20|200|300';
var array = string.split('|');
//array[0] = '5';
//array[array.length-1] = '300';
It's not regex I know, but I've always found split easier to work with in most cases.
Convert the string into an array using split() method
var str="5|10|20|200|300";
var res_array = str.split("|");
now to get first and last value of an array:::
alert("First value is"+ res_array[0]);
alert("Last value is"+ res_array[arr.length - 1]);