Ruby Regex for String,其中包含X个整数数量

发布于 2025-01-23 23:52:56 字数 159 浏览 3 评论 0原文

我想制作一个与包含X整数数字的字符串相匹配的Ruby Regex。我希望字符串也能够包含其他单词。

例子: 如果 x = 2 ,则应匹配: “每小时有3辆车超过45英里”

第一个整数为3,第二个整数为45。

I want to craft a ruby regex that matches strings that contain exactly x integer numbers. I want the string to also be able to contain other words as well.

Example:
If x = 2, the following should match:
"There were 3 cars going over 45 miles per hour"

where the first integer is 3 and the second integer is 45.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一紙繁鸢 2025-01-30 23:52:56

我会写的

str = "There were 3 cars going over 45 miles per hour"
str.scan(/\d+/).size == 2
  #=> true

str.gsub(/\d+/).count == 2
  #=> true

后者具有优势,即str.gsub(/\ d+)返回枚举器,而str.Str.scan(/\ d+/)创建一个临时数组。

请参阅 string#gsub 进行论点,但没有块, enum of noreferrer“> /a>。

I would write

str = "There were 3 cars going over 45 miles per hour"
str.scan(/\d+/).size == 2
  #=> true

or

str.gsub(/\d+/).count == 2
  #=> true

The latter has the advantage that str.gsub(/\d+) returns an enumerator, whereas str.scan(/\d+/) creates a temporary array.

See the form of String#gsub that takes an argument but no block, and Enumerable#count.

手长情犹 2025-01-30 23:52:56

您可以使用一般的正则方式:

^\D*(?:\d+\D+){2}$

您可以将{2}替换为字符串中的许多数字。这是一个工作 demo

You may use the general regex pattern:

^\D*(?:\d+\D+){2}$

You may replace the {2} with however many numbers you expect in the string. Here is a working demo.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文