I am trying to create a RegEx rule to find side-to-side digits in a number. For example given an array of:
const nums = [1, 2, 33, 4, 22, 5, 66, 112];
I want to remove the digits [33, 22, 66, 112]
from the array because they have repeated digits.
I tried the /[0-9/{2}
but this seems to not work.
You can use filter
with regex pattern ( which uses capturing group and back reference )
[0-9]{2}
- Means match any digit from 0 to 9 two times which doesn't guaranty repeated digits
([0-9])\\1
([0-9])
- Means match digit 0 to 9 ( captured group 1 ) \\1
- should match the same value as the captured group 1 const nums = [1, 2, 33, 4, 22, 5, 66, 112]; let nonRepeated = nums.filter(num => !/([0-9])\\1/.test(""+num)) // can replace with !/([0-9])\\1/.test(num) because it implicit coerce to string console.log(nonRepeated)
像这样使用\\1
反向引用:
/(\d)\1+/
You can use filter and includes
const nums = [1, 2, 33, 4, 22, 5, 66, 112];
result = nums.filter(v => ![33, 22, 66, 112].includes(v));
the shortest approach is just to check if a same character is followed by itselft. No need for checking dor digits, because the value contains only digits or a dot (or E
or space). The last occurs only once.
var nums = [1, 2, 33, 4, 22, 5, 66, 112], nonRepeated = nums.filter(v => !/(.)\\1/.test(v)); console.log(nonRepeated);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.