var number = '731231';
var myRegex = /[0-6]/;
console.log(myRegex.test(number));
Can anyone explain this ?
IMO the regex written as [0-6] will only check for numbers between 0 and 6 but in the above case the value as large as 731231 is also evaluated to be true
Your regex matches, when there is any such digit present. If you want to match only such digits, use
/^[0-6]+$/
This matches a string with any number of digits from 0-6. If you want a single digit, omit the +:
/^[0-6]$/
You're checking if there is somewhere a number between 0 and 6, which is the case.
var number = '731231';
var myRegex = /^[0-6]+$/;
console.log(myRegex.test(number));
UPDATE
Though, if you want the string to match a number satisfying the rule 0 >= N <= 6
This would be what you want
var myRegex = /^[0-6]$/;
Yiu should use
var myRegex = /^[0-6]$/;
you're looking for a string that starts ^ then contains one 0..6 digit and immediately ends $
Your implementation /[0-6]/ is looking for a 0..6 digit anywhere within the string, and that's why 731231 meets this criterium.
Your regex is checking to see if one of the following appears in the string:
0, 1, 2, 3, 4, 5 or 6
and that is true because there is 1, 2 and 3 in there.
If you want to check that the whole string is a number then you could use:
var myRegex = /^[0-9]+$/;
Related
I am working on a Chat bot for discord that has an addition calculator.... I am currently trying to find the .indexOf the first time a number appears in the string... For ex: !add 1 + 1 would be the command to add 1 and 1... I have an array that I use that contains all single numbers ex:
const singleNumbers = [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
];
when I get the string back I am using
for (const num of singleNumbers){
const num1 = msg.content.indexOf(num,);
const add = '+';
const locationOfAdd = msg.content.indexOf(add,);
const num2 = msg.content.indexOf(num,locationOfAdd);
const add1 = msg.content.slice(num1,) * 1;
const add2 = msg.content.slice(num2,) * 1;
msg.reply(add1 + add2);
}
When I run this... It for some reason will only use the first number of the Array so the numbers I use in !add 1 + 1 have to start with 0... so !add 01 + 01 which in math is fine... but for simplicity how do I make it be able to start with any number in the array rather than the first... If you don't know discord.js,
msg.content
Is the string returned so if I type in chat...
Hey Guys what's goin on?
it would return as a String ("Hey Guys what's goin on?")...
To sum this all up... I am wondering how to make my const num that I declared in my for of loop check for all the numbers in its array rather than just the first in my case 0.
If you just want to find the index for the first digit str.search(/[0-9]/) or str.match/[0-9]/).index.
Using regex to extract the numbers, and reduce to add them:
match on: string starts with !add, at least one space, at least one digit as a capture group, optional space and a + sign, another series of digits as a capture group.
You get an array with [full match, digit group 1, digit group 2]. I slice off the full match, and then use reduce to (+x converts the string to a number; you could also use Number(x)) to add each number and collect it in sum.
const sum = msg.content.match(/^!add\s+(\d+)\s*\+\s*(\d+)/).slice(1).reduce((sum,x)=>+x+sum,0)
Note: \d is the same as [0-9]
JavaScript.info RegExp tutorial
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 extract the integers from a string.
String :
Str = "(Start = 10) AND (End_ = 40)"
Note: The integers here can range from 1 - 999, single digit to three digits
Desired Output:
No1 = 10
No2 = 40
This code will get you what you want, an array of numbers found in the string.
Explanation
The regular expression looks for a single number 1 through 9 [1-9] followed by 0, 1, or 2 {0,2} numbers between 0 through 9 [0-9]. The g means global, which instructs match() to check the entire string and not stop at the first match.
Code
var str = "(Start = 10) AND (End_ = 40)";
var numbers = str.match(/[1-9][0-9]{0,2}/g);
console.log(numbers);
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.
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.