1-50 不带小数点的正则表达式
我正在寻找一个正则表达式,它可以匹配 1 到 50 之间的任何数字。到目前为止,我已经找到了示例,但它们都允许字符串包含小数点,但我不想包含小数点。所以 1,13,24,50 可以,但 1. 等不行。有我可以使用的 REGEXP 吗?
提前致谢, 蒂姆
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
试试这个:
更新:
现在我看到问题已经更新为引用 MySQL,这显着改变了事情。上述正则表达式使用了 MySQL 不支持的非捕获括号。但这也引出了一个问题:你真的应该使用正则表达式来解决这个问题吗?我们确实必须看看您如何存储必须在 1 到 50 之间的数字。它们是
varchar
吗?它们是 int 吗?我将演示如何以两种方式解决这个问题。首先,我将设置一个带有索引的测试表:现在将一些测试数据放入其中,以确保涵盖所有边缘情况:
现在,这里有一个查询将解决您的问题,假设您的数字作为字符串存储在
varchar_number
列:这可行,但在大型数据集上表现不佳,因为即使存在索引,它也无法使用索引。 MySQL 必须对表中的每一行运行一次正则表达式。假设 1 到 50 之间的数字以
int
形式存储在int_number
列中。您可以简单地这样做:该查询将执行良好,因为它可以使用索引,并且它也更具可读性和更易于维护。全面获胜。
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
varchar
s? Are theyint
s? 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_number
column: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
int
s in theint_number
column. 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.
编辑: 由于 OP 的后续评论表明这是针对 MySQL 的,因此我更改了指定模式的语法。
即:
编辑:上面允许 0(和 00),但您肯定不想要。因此,假设您实际上并不希望允许使用前导零:
编辑: 由于 OP 的后续评论表明这是针对 MySQL 的,因此我更改了指定模式的语法。
Edit: As the OP's later comments indicate that this is for MySQL, I've changed the syntax for specifying the pattern.
That is:
Edit: The above allows 0 (and 00) which you surely don't want. So, assuming you didn't really want leading zeros allowed anyhow:
Edit: As the OP's later comments indicate that this is for MySQL, I've changed the syntax for specifying the pattern.
^([1-9]|[1-4][0-9]|50)$
^([1-9]|[1-4][0-9]|50)$
尝试这个
将执行以下操作
try this one
will Do Following
使用 Perl6::Rules 进行“作弊”:
或者在 Perl 5.10 及更高版本中,
"Cheating" with Perl6::Rules:
Or in Perl 5.10 and up,