有没有办法在 Ruby on Rails 中将正则表达式更改为一系列数字? [英] Is there a way of changing regular expressions to a range of numbers in Ruby on Rails?

查看:43
本文介绍了有没有办法在 Ruby on Rails 中将正则表达式更改为一系列数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常需要在正则表达式中创建数字范围.所以例如'[2-3][0-9]' 是 20-39 之间的数字范围.为了仔细检查我的范围,我通常使用 Linux 命令.对于[2-3][0-9]",Linux 命令将是:

I often need to create range of numbers in regular expressions. So e.g. '[2-3][0-9]' is range of numbers between 20-39. To double check my range, I normally use Linux command. For '[2-3][0-9]' the Linux command would be:

seq 1 40|egrep '[2-3][0-9]' 

为我打印所有数字.

Ruby on Rails 中是否有类似于seq 1 40|egrep"的东西可以为我打印数字?

Is there anything similar to "seq 1 40|egrep" in Ruby on Rails that would print the numbers for me?

这会非常方便,因为我更喜欢可以在 Rails 中创建自己的漂亮 GUI.

It would be quite handy, because I would prefer a nice GUI that I could create myself in Rails.

推荐答案

使用正则表达式查看数字是否在特定范围内首先是代码异味.你采取了错误的方法(除非你在做代码高尔夫或其他一些hacky 的事情).您不应尝试构建旨在匹配特定范围内的数字的正则表达式.

Using a regex to see if a number is in a certain range is code smell in the first place. You are taking the wrong approach (unless you are doing code golf or some other hacky thing). You should not try to build a regex that is intended to match a number in a certain range.

我建议您不要在检查部分使用正则表达式.相反,只需按原样提取数字(使用正则表达式),然后以更直接的方式查看它是否在一个范围内.假设您有一个字符串 s.使用正则表达式中的 (\d+) 提取它的数字部分.然后取出那部分(如果它是正则表达式中的第一个括号,则它是$1),将其转换为数字,并检查它是否在范围内.

I recommend you not to use a regex for the checking part. Rather, just extract the number as is (using a regex), and see if it is within a range in a more direct way. Suppose you have a string s. Extract the number part of it using (\d+) within a regex . Then take out that part (if it is the first parenthesis in the regex, then it is $1), convert it into a number, and check if it fits in the range.

(20..39).cover?($1.to_i)

这篇关于有没有办法在 Ruby on Rails 中将正则表达式更改为一系列数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆