Can you match two sets of equal length, and how?

淺唱寂寞╮ 提交于 2021-02-16 15:23:20

问题


Is it possible to create a regex to match two sets with equal length? For example: I would like to match aabb and aaaabbbb but not aaaabb. What I want is something like [a]+[b]+, but with with both of those having equal length, so something like [a]{x}[b]{x} where x is a possible length. Is it possible to do this with one javascript regex, should I use multiple regexes for the multiple possibilities (I dont think I will need to check for length 32 or higher) or should I code it in myself?


回答1:


You can just split the two strings and check if both contain the same letter.

var rgx = /^(.)\1*$/, // makes sure all the characters are same
    str = "aaabbb", // define your string
    len = str.length / 2, // divide the length by two assuming it is even
    firstHalf = str.slice(0, len), 
    secondHalf = str.slice(len);

var isValid = (rgx.test(firstHalf) == rgx.test(secondHalf));


来源:https://stackoverflow.com/questions/28783450/can-you-match-two-sets-of-equal-length-and-how

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!