I want to set a regex test to test the string is 1.1 or 1.1.1 or 1.1.1.1 etc but I only know this only accept 1 and .
/^[1\.]+$/.test(string)
If I test 1.11.1, it still return true.
I want to set a regex test to test the string is 1.1 or 1.1.1 or 1.1.1.1 etc but I only know this only accept 1 and .
/^[1\.]+$/.test(string)
If I test 1.11.1, it still return true.
If the string only accepts zero and one, but can not contain 11 you can use a negative look ahead to assert not 11.
Note that you don't have to escape the . in the character class.
^(?!.*11)[.1]+$
const regex = /^(?!.*11)[.1]+$/;
[
"1.1",
"1.1.1",
"1.1.1.1",
"...",
"..1111",
"1.1.....",
"...1..1.."
].forEach(s => {
const m = regex.test(s);
if (m) {
console.log(`Match --> ${s}`);
} else {
console.log(`No match --> ${s}`);
}
})
If there should be at least a . and a 1 present, you can add asserting a . and match at least a 1
^(?!.*11)(?=1*\.)[.]*1[.1]*$
const regex = /^(?!.*11)(?=1*\.)[.]*1[.1]*$/;
[
"1.1",
"1.1.1",
"1.1.1.1",
"...",
"..1111",
"1.1.....",
"...1..1.."
].forEach(s => {
const m = regex.test(s);
if (m) {
console.log(`Match --> ${s}`);
} else {
console.log(`No match --> ${s}`);
}
})
Try using ^1(?:\.1)*$:
var input = ["1", "1.1", "1.1.1.1", "1.2.3.4", "1.11", "hot dog"];
for (var i=0; i < input.length; i++) {
if (/^1(?:\.1)*$/.test(input[i])) {
result = "MATCH";
}
else {
result = "NO MATCH";
}
console.log(input[i] + " => " + result);
}
Another approach you might want to think about using here is to build a DFA. Since the regex is so simple, it does not take much effort:
function check(a){
let isChecked = true;
let STATE = 0;
for(let i = 0; i < a.length; i++){
if(STATE === 0 && a[i] === '1') STATE = 1;
else if(STATE === 1 && a[i] === '.') STATE = 0;
else{ isChecked = false; }
}
if(STATE === 0) isChecked = false;
return isChecked;
}
let arr = ['1', '1.11.1', '1.1.1.1', 'a.vad.bsadf.1', '1.1.111.1']
arr.forEach((a) => console.log(check(a)))