简体   繁体   English

这个非常简单的正则表达式有什么问题?

[英]What is wrong with this extremely simple regex?

I'm trying to test that a regex will match a 2-digit number. 我试图测试一个正则表达式将匹配一个2位数字。 I get: 我明白了:

11 =~ /^\d{1,2}$/
# => nil

Yet the regex works flawlessly on Rubular. 然而正则表达式在Rubular上完美无缺。 What am I doing wrong? 我究竟做错了什么?

The problem is that you are testing the regex against a number and not a string. 问题是您正在针对数字而不是字符串测试正则表达式。 Regexes are intended for matching strings. 正则表达式用于匹配字符串。 Simply: 只是:

'11' =~ /^\d{1,2}$/

or 要么

11.to_s =~ /^\d{1,2}$/

You are calling Kernel#=~ , which always returns nil . 你正在调用Kernel#=~ ,它总是返回nil

Rubular does not interpret your input as Ruby code, it interprets is as string literal. Rubular没有将您的输入解释为Ruby代码,它解释为字符串文字。 That is why it works there. 这就是它在那里工作的原因。

您正在对数字而不是字符串应用正则表达式,因此将其转换为字符串并再次尝试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM