I want to check if an input is a valid bra measurement. In the US, bra sizes are written with an even number 28-48 and a letter A-I, AAA, AA, DD, DDD, HH or HHH. The EU, Japan and Australia use different numbers and patterns, ex. 90C C90 and DD6.
-I want to split the letters and digits, check that the letter is between A - I or AA, AAA, DD, DDD, HH or HHH, and that the number is 28 - 48 (even numbers only), 60-115 (increments of 5, so 65, 70, 75, etc.) or 6-28 even numbers only.
var input = $("#form_input").val("");
var bust = input.match(/[\d\.]+|\D+/g);
var vol = bust[0];
var band = bust[1];
I can write a long test condition:
if ((vol > 28 && vol < 48) && band == "AAA" || band == "AA" || band == "A" || band == "B" || etc.) { //some code
} else { error message" }```
How do I shorten this and do the above things using regex?
It is a bit of a long pattern with the alternatives, but you can easily adjust the ranges if something is missing or matches too much.
You can first check if the pattern matches using test. To get the band and the vol matches, one option is to extract either the digits or the uppercase chars from the match as there are matches for example for 90C and C90
^(?:(?:28|3[02468]|4[02468])(?:AA?|[BC]|D{1,4}|[E-I])|(?:[6-9][05]|1[01][05])(?:AA?|[BC]|DD?|[E-I])|[A-I](?:[6-9][05]|1[01][05])|(?:[68]|1[02468]|2[0246])(?:AA?|[BC]|DD?|[E-I]))$
Explanation
^ Start of string(?: Non capture group for the alternatives
(?:28|3[02468]|4[02468]) Match from 28 - 48 in steps of 2(?:AA?|[BC]|D{1,4}|[E-I]) Match AA, A, B, C, 1-4 times a D or a range E-I| Or(?:[6-9][05]|1[01][05]) Match from 60 - 115 insteps of 5(?:AA?|[BC]|DD?|[E-I]) Match AA, A, B, C DD, D or a range E-I| Or[A-I](?:[6-9][05]|1[01][05]) Match a range A-I and a number 60 - 115 in steps of 5| Or(?:[68]|1[02468]|2[0246]) Match from 6 - 26 in steps of 2(?:AA?|[BC]|DD?|[E-I]) Match AA, A, B, C, DD, D or a range E-I) Close alternation$ End of stringRegex demo
const pattern = /^(?:(?:28|3[02468]|4[02468])(?:AA?|[BC]|D{1,4}|[E-I])|(?:[6-9][05]|1[01][05])(?:AA?|[BC]|DD?|[E-I])|[A-I](?:[6-9][05]|1[01][05])|(?:[68]|1[02468]|2[0246])(?:AA?|[BC]|DD?|[E-I]))$/;
const str = `28A
28AA
30B
34AA
36DDDD
D70
I115
A70
H80
6AA
26I
`;
str.split('\n').forEach(s => {
if (pattern.test(s)) {
console.log(`Match: ${s}`);
let vol = s.match(/\d+/)[0];
let band = s.match(/[A-Z]+/)[0];
console.log(`vol: ${vol}`);
console.log(`band: ${band}`);
console.log("---------------------------------------");
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With