I am looking for a regular expression that will match any number from 1 to 50 inclusive. So far, I have found examples but they all allow the string to contain a decimal point, which I do not want to include. So 1,13,24,50 are OK but 1. ,etc are not. Is there a REGEXP that I can use?
Thanks in advance,
Tim
Try this:
UPDATE:
Now that I see the question has been updated to refer to MySQL, this changes things significantly. The above-mentioned regular expression uses non-capturing parens which are not supported by MySQL. But it also begs the question; should you really be using regular expressions to solve this problem? We really have to look at how you are storing your numbers that must be between 1 and 50. Are they
varchars? Are theyints? I’ll demonstrate how to solve it both ways. First I’ll set up a test table with indexes:Now put some test data into it making sure all our edge cases are covered:
And now, here is a query that will solve your problem assuming that your numbers are stored as strings in the
varchar_numbercolumn:This works but it will perform poorly on large data sets because it can’t use an index even if one is present. MySQL must run the regular expression once for every row in the table. Suppose your numbers between 1 and 50 were stored as
ints in theint_numbercolumn. You could simply do this:This query will perform well because it can use an index and it’s also more readable and more maintainable. Wins all around.