How to get a regex that does all of this and returns a boolean value as answer.
1: gets numbers separated by any delimiter (space or any non numeric character), 2: strips off all numbers in that array less than 5 digits and creates new array 3: gives boolean result as to whether the new array has less than 4 elements(that determines whether it is valid). 4: If the input string has only characters, then the regex test should pass
const goodlist = "111,256 323| 78987 & 65434 727272727"; // should be good
const badlist = "111256333 323666666a| 78987333333 & 6543 727272727";
let numberPattern = /\d /g;
let numbersArr1 = goodlist.match(numberPattern);
let filArr1 = numbersArr1.filter((w) => w.length > 4);
let numbersArr2 = badlist.match(numberPattern);
let filArr2 = numbersArr2.filter((w) => w.length > 4);
console.log(numbersArr1, numbersArr2);
const isGoodListOK = filArr1.length < 4;
const isBadListOK = filArr2.length < 4;
document.getElementById("app").innerHTML = `
<div>Input string: ${goodlist}</div>
<br/>
<div>Formatted input: ${numbersArr1} : Filtered Array: ${filArr1}</div>
div>is this list ok: ${isGoodListOK}</div>
<br/>
<br/>
<br/>
<br/>
<div>Input string: ${badlist}</div>
<br/>
<div>Formatted input: ${numbersArr2} : Filtered Array: ${filArr2}</div>
<div>is this list ok: ${isBadListOK}</div>
I got this all done in javscript, but would like a single regex
https://codesandbox.io/s/simple-regex-to-check-date-format-forked-l1c6pl?file=/src/index.js
CodePudding user response:
You might use a single pattern that asserts not 4 times 4 or more digits, and then match at least a single occurrence.
^(?!(?:.*?\b\d{4,}\b){4}).
Explanation
^
Start of string(?!
Negative lookahead(?:
Non capture group.*?
Match any character, as few as possible\b\d{4,}\b
Then match 4 or more digits between word boundaries){4}
Close the non capture group and repeat it 4 times
)
Close the lookahead.
Match either till the first occurrence of 4 digits between word boundaries, or match the whole line consisting only of spaces or characters A-Za-z
const goodlist = "111,256 323| 78987 & 65434 727272727"; // should be good
const badlist = "111256333 323666666a| 78987333333 & 6543 727272727";
const goodlist2 = 'Harry Potter'
const goodlist3 = '123 | 111 | 233 | 534'
const regex = /^(?!(?:.*?\b\d{4,}\b){4}). /;
console.log(regex.test(goodlist));
console.log(regex.test(badlist));
console.log(regex.test(goodlist2));
console.log(regex.test(goodlist3));