Comment to 'Regex for height , weight and body type'
  • Mayki, greetings;

    Listen to Leonid. :)

    If you still need or want regex, I have provided non-capturing regexes below. These are written in JavaScript. Although the notation is the same for other languages, the way the regex is called and executed is different. 

    Non-capturing means they specifically do not read back to you the exact answer; instead each rings true if the response is in there and null or undefined if false. I made it non-capturing, because it's simpler that way. If using JavaScript, this is how to test:

    Pseudo test code: if (re.exec(somefield.value)) {console.log('valid input!);}

    Height:

    re = /^(?:15(?:0|5)cm\s(?:\-|or)) | (?:16(?:0|5)cm\s\-) | (?:17(?:0|5)cm\s\-) | (?:18(?:0|5)cm\s\-) | (?:19(?:0|5)cm\s\-) | (?:200cm and)/;

    Weight:

    Your weight pairs confuse me, because on the one hand you increase by 5, i.e., from 45 to 50; but the next pair increases 10, from 50-60; then the last two examples look as if they have increased by only 5 again. Therefore I'm thinking you meant the 50-60 pair should be 50 to 55, followed by 55-60.

    The following regex assumes you are going in increments of 5, not 10:

     re = /(?:45kg\s(?:\-|or)) | (?:5(?:0|5)kg\s\-) | (?:6(?:0|5)kg\s\-) | (?:7(?:0|5)kg\s\-) | (?:8(?:0|5)kg\s\-) | (?:9(?:0|5)kg\s\-) | (?:10(?:0|5)kg\s\-) | (?:11(?:0|5)kg\s\-) | (?:120kg or)/;

    Body Type:

    re = /(?:(?:very\s)?(fat)|(slim))|(?:fit)|(?:A(?:(?:thletic)|(?:verage)|(?:mple)))/i;

    I have tested all these in text files using grep, which uses "regular expressions."

    There are many tutorials on regex; just practice, test, and test again. There is usually more than one way to write your tests. If you wonder what the (?:15(?:0|5) kind of notation means, the "?:" means do not capture this group. 15 is the first part of both 150 and 155, starting numbers in three instances. The pipe symbol means "or." Thus 0|5 means zero or five following the 15. That means one group takes care of both fields that start with 150 and fields that start with 155; and so forth. The same concept was used for weight. The height and weight regexes just look at the first number, not the end of each range. If you want to test the end of each range, too, you might as well do a string test rather than regex. The body type regex "ignores" case. If you want the Body type not to ignore case, then, remove the letter "i" after the ending slash; and capitalize Very, Fat, Slip, and Fit, only. (The A-words are already using a capital A.)

    HTH