问题
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