Regular expression to match 0 or 1 - javascript

I need a regexp to match either 0 or 1 entered into a field and no other characters at all, neither numeric nor alphas. How can I do it?

Single character, 0 or 1:
/^[01]$/
Multiple 0s or 1s (any order, no other characters):
/^[01]+$/g
Demo (Just add a + for the second example. The gm at the end in the demo is just for the example because there are multiple lines for test cases)

A simple 0|1 expression should work.

([01])
http://rubular.com/r/TMu6vsx6Dn
If you only want the first occurrence, this will work as well.
(^[01])
http://rubular.com/r/i3brvRutCg

Try this regex: /^(0|1)$/
Example:
/^(0|1)$/.test(0); // true
/^(0|1)$/.test(1); // true
/^(0|1)$/.test(2); // false
/^(0|1)$/.test(1001) // false

I would suggest simple string evaluation here since you have only two known acceptable values in the input string:
var input; // Your input string assume it is populated elsewhere
if (input === '0' || input === '1') {
// Pass
}
Note the use of strict string comparison here to eliminate matches with truthy/falsey values.
If you are really hell-bent on a regex, try:
/^[01]$/
The key here is the beginning ^ and ending $ anchors.

Related

JavaScript regex inline validation for basic calculation string with one operator

I've written a basic 2 operand calculator app (+ - * /) that uses a couple of inline regex validations to filter away invalid characters as they are typed.
An example looks like:
//check if operator is present
if(/[+\-*\/]/.test(display1.textContent)){
//validate the string each time a new character is added
if(!/^\d+\.?\d*[+\-*\/]?\d*\.?\d*$/.test(display1.textContent)){
console.log('invalid')
return false
}
//validate the string character by character before operator
} else {
if(!/^\d+\.?\d*$/.test(display1.textContent)){
console.log('invalid')
return false
}
}
In the above, a valid character doesn't return false:
23.4x0.00025 (no false returned and hence the string is typed out)
But, if an invalid character is typed the function returns false and the input is filtered away:
23.4x0.(x) x at the end returns a false so is filtered (only one operator allowed per calculation)
23.4x0. is typed
It works pretty well but allows for the following which I would like to deal with:
2.+.1
I would prefer 2.0+0.1
My regex would need an if-then-else conditional stating that if the current character is '.' then the next character must be a number else the next char can be number|.|operator. Or if the current character is [+-*/] then the next character must be a number, else the next char can be any char (while following the overall logic).
The tricky part is that the logic must process the string as it is typed character by character and validate at each addition (and be accurate), not at the end when the string is complete.
if-then-else regex is not supported in JavaScript (which I think would satisfy my needs) so I need to use another approach whilst remaining within the JS domain.
Any suggestions about this specific problem would be really helpful.
Thanks
https://github.com/jdineley/Project-calculator
Thanks #trincot for the tips using capturing groups and look around. This helped me write what I needed:
https://regex101.com/r/khUd8H/1
git hub app is updated and works as desired. Now just need to make it pretty!
For ensuring that an operator is not allowed when the preceding number ended in a point, you can insert a positive look behind in your regex that requires the character before an operator to always be a digit: (?<=\d)
Demo:
const validate = s => /^(\d+(\.\d*)?((?<=\d)[+*/-]|$))*$/.test(s);
document.querySelector("input").addEventListener("input", function () {
this.style.backgroundColor = validate(this.value) ? "" : "orange";
});
Input: <input>

use replace to remove chars not existing in a regex match

I'am trying to allow following pattern for a single html input box with javascript regex
-int (aka any minus number so long it not followed by a zero and is in the first position)
0 (a single zero is allowed)
int (is allowed)
I use this function the remove anything that doesn't match it
$('.dointcheck').live('keyup',
function () {
$(this).val($(this).val().replace((/^((?!:([1-9-]?[0-9])).)/g), ''));
if ($(this).val().length == 0) {
$(this).val(0);
}
});
which doesn't work.
Other examples is:
/[^-0-9]/g it removes any non valid chars but doesnt check if the minus is the beginning and is followed by a zero. It allows minus everywhere in the string
(/^((?!:([1-9-]?[0-9])).)/g Don't allow none.
[^1-9-]?[^0-9]* Allow all...
I think I'am missing something.. Any suggestions would be most appreciated..
You may try this regex
^(0).*|^(-?)([1-9]\d*)?.*|^.*
and replace it with $1$2$3 after input
document.querySelector('input').addEventListener('input', ({ target }) => target.value = target.value.replace(/^(0).*|^(-)?([1-9]\d*)?.*|^.*/g, '$1$2$3'));
<input />
It has three tests:
^(0).* // if it starts with 0, discard everything after it
^(-)?([1-9]\d*)?.* // otherwise it can only starts with a -, or any number that is not a 0. Then followed by other digits, then discard everything after it
^.* // if previous rules are not matched, discard everything
In short:
generally only -, 0-9 are allowed.
if you type a 0 first, nothing will be allowed after.
if you type a 1-9 first, only numbers are allowed after.
if you type a - first, only 1-9 is allowed next, then any digit is allowed after.
I changed your regexp and made it a bit more modular and it worked fine.
function toValidNumber(int) {
return (/^\s*[+-]?(\d+|\d*\.\d+|\d+\.\d*)([Ee][+-]?\d+)?\s*$/).test(int) ? int : 0;
}
$('.dointcheck').live('keyup',
function () {
$(this).val(toValidNumber($(this).val()));
});
Orginal RegEXP in Stackoverflow

How to look for a pattern that might be missing some characters, but following a certain order?

I am trying to make a validation for "KQkq" <or> "-", in the first case, any of the letters can be missing (expect all of them, in which case it should be "-"). The order of the characters is also important.
So quick examples of legal examples are:
-
Kkq
q
This is for a Chess FEN validation, I have validated the first two parts using:.
var fen_parts = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
fen_parts = fen_parts.split(" ");
if(!fen_parts[0].replace(/[1-8/pnbrqk]/gi,"").length
&& !fen_parts[1].replace(/[wb]/,"").length
&& !fen_parts[2].replace(/[kq-]/gi,"").length /*not working, allows KKKKKQkq to be valid*/
){
//...
}
But simply using /[kq-]/gi to validate the third part allows too many things to be introduced, here are some quick examples of illegal examples:
KKKKQkq (there is more than one K)
QK (order is incorrect)
You can do
-|K?Q?k?q?
though you will need to do a second test to ensure that the input is not empty. Alternatively, using only regex:
KQ?k?q?|Qk?q?|kq?|q|-
This seems to work for me...
^(-|(K)?((?!\2)Q)?((?!\2\3)k)?((?!\2\3\4)q)?)$
A .match() returns null if the expression did not match. In that case you can use the logical OR to default to an array with an empty-string (a structure similar to the one returned by .match() on a successful match), which will allow you to check the length of the matched expression. The length will be 0 if the expression did not match, or K?Q?k?q? matched the empty string. If the pattern matches, the length will be > 0. in code:
("KQkq".match(/^(?:K?Q?k?q?|-)$/) || [""])[0].length
Because | is "stronger" than you'd expect, it is necessary to wrap your actual expression in a non-capturing group (?:).
Having answered the question, let's have a look at the rest of your code:
if (!fen_parts[0].replace(/[1-8/pnbrqk]/gi,"").length)
is, from the javascript's perspective equivalent to
if (!fen_parts[0].match(/[^1-8/pnbrqk]/gi))
which translates to "false if any character but 1-8/pnbrqk". This notation is not only simpler to read, it also executes faster as there is no unnecessary string mutation (replace) and computation (length) going on.

Can I chain a substring check in javascript?

I am using the following code:
if (store.getItem('TopicID') != "00")
TopidID is always 4 digits and what I need to do is change this to check if the last two digits are "00".
Can I do this as part of the above by just adding ".substring(from, to)" or do I need to put this into a variable and then check the variable?
Use if (!/00$/.test(store.getItem('TopicID')) to check for the last 2 digits not forming '00'. That way the length of the value of store.getItem('TopicID') doesn't matter, you always check for the last two characters of the value, and you don't need the substring 'chaining'.
By the way, I supposed store.getItem('TopicID') returns a String here.
To be complete and in response to Paul Phillips comment: in !/00$/.test([somestring]), /00$/ is a Regular Expression, a special text string for describing a search pattern. In this case it means: for the string resulting from store.getItem('TopicID'), check if you can find 2 consecutive zero's, where the $-sign means 'check for that pattern at the end of the string'.
To be even more complete on the subject of 'chaining': as long as a method is contained by the object to chain, everything can be chained. A completely nonsensical example of that:
Number(/00$/.test('0231')) //convert a boolean to a Number
.toFixed(2) //a Number has the toFixed method
.split('.')[1] //toFixed returns a String, which has method split
.substr(1) //the second element is a string, so substr applies
.concat(' world') //still a string, so concat will do
.split(' ') //string, so split works
.join(' hello ') //from split an array emerged, so join applies
;
//=> result of this chain: '0 hello world'
Can I do this as part of the above by just adding ".substring(from, to)"
Yes, you can. You got the wrong syntax, though.
if (store.getItem('TopicID').substring( 2 ) != "00")
Chaining it would work. So would extracting a local variable. So no, you don't need to. Do it if you think it makes the code more readable.
you can do using slice too
if (store.getItem('TopicID').slice(2,4) != "00") {
// Do Your Stuff
}
Try to use substr or substring with negative start:
if ( store.getItem('TopicID').substr(-2) !== "00" ){...}
or
if ( store.getItem('TopicID').substring(-2) !== "00" ){...}
if it's four digits, you can use
if (store.getItem('TopicID') % 100)
var yourString = (store.getItem('TopicID'))
if(yourString.substring((yourString.length - 2), 2) == "00")
The code above doesn't care how long your string is. It gets the last two digits and compare to "00"

Regular expression match !

I am trying to find for the string of the format abc1234. I can compare character taking at each index whether is alpha or numeric and get the result. Instead wrote for a pattern match but couldn't succeed. Could some one know me where I am going wrong ?
var clid = "mxv4013" ;
if(clid.match("/[a-z]{3}(?=[0-9]{4})/i") != null){
alert("success") ;
}
Thanks.
You don't need the quotes, JavaScript has regex literals:
var clid = "mxv4013" ;
if(clid.match(/[a-z]{3}(?=[0-9]{4})/i)){
alert("success") ;
}
You can also remove the != null check - match will return a true value on success and a falsy value on fail. In addition, the look-ahead is a little strange, you can use /[a-z]{3}\d{4}/i, or, to validate the whole string and avoid partial matching, /^[a-z]{3}\d{4}$/i.
String#match takes a regexp instead of a string for its parameter.
You are looking for:
'mxv4013'.match(/[a-z]{3}(?=[0-9]{4})/i)
Or, more simply:
'mxv4013'.match(/[a-z]{3}\d{4})/i)

Categories

Resources