Home > OS >  Regular expression to check any character in more than two times
Regular expression to check any character in more than two times

Time:11-29

I'm looking for a simple regular expression to match same character in the string more than two times likes following in java script. (Number 1 is three times) 112561

CodePudding user response:

The following regex can be used for this purpose:

.*(.).*\1.*\1.*

CodePudding user response:

This will check if a character is repeated more than 2 times in a string. Note that this also does not use * which is a cause for performance issues in JavaScript.

console.log(/. ?(.)((?:.) ?\1){1,}/.test('abcZdefZghiZ'))
console.log(/. ?(.)((?:.) ?\1){1,}/.test('112561'))
console.log(/. ?(.)((?:.) ?\1){1,}/.test('12561'))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You could check if a group is more than tow times in the array.

console.log(/(.).*\1.*\1/g.test('12561'));
console.log(/(.).*\1.*\1/g.test('112561'));
console.log(/(.).*\1.*\1/g.test('2125611'));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related