When I match a number using a regular expression I get it as a string:
当我使用正则表达式匹配数字时,我将其作为字符串获取:
?> 'TestingSubject2981'.match /\d+$/
=> #<MatchData "2981">
Is it somehow possible to get the number as an integer without some to_i
s?
是否有可能在没有某些to_is的情况下将数字作为整数?
3 个解决方案
#1
2
The issue is that regular expressions only work on strings, not on other data types.
问题是正则表达式仅适用于字符串,而不适用于其他数据类型。
A regex has patterns to match numbers, but those still only find the characters that represent the number, not the binary values that we'd use for math. Once the engine returns the matches, they're still characters, so we have to use to_i
to convert them to their binary representations.
正则表达式具有匹配数字的模式,但那些仍然只能找到代表数字的字符,而不是我们用于数学的二进制值。一旦引擎返回匹配项,它们仍然是字符,所以我们必须使用to_i将它们转换为二进制表示形式。
MMM-kay?
#2
1
Regular expressions are not supposed to convert strings to integers (or any other class for that matter). The only way I can see is using the String#to_i method. And I can't see why you would avoid it.
正则表达式不应该将字符串转换为整数(或任何其他类)。我能看到的唯一方法是使用String#to_i方法。我不明白为什么你会避免它。
#3
0
You can also use to get number from string:
您还可以使用从字符串中获取数字:
'TestingSubject2981'.scan(/\d+/)[0].to_i
#1
2
The issue is that regular expressions only work on strings, not on other data types.
问题是正则表达式仅适用于字符串,而不适用于其他数据类型。
A regex has patterns to match numbers, but those still only find the characters that represent the number, not the binary values that we'd use for math. Once the engine returns the matches, they're still characters, so we have to use to_i
to convert them to their binary representations.
正则表达式具有匹配数字的模式,但那些仍然只能找到代表数字的字符,而不是我们用于数学的二进制值。一旦引擎返回匹配项,它们仍然是字符,所以我们必须使用to_i将它们转换为二进制表示形式。
MMM-kay?
#2
1
Regular expressions are not supposed to convert strings to integers (or any other class for that matter). The only way I can see is using the String#to_i method. And I can't see why you would avoid it.
正则表达式不应该将字符串转换为整数(或任何其他类)。我能看到的唯一方法是使用String#to_i方法。我不明白为什么你会避免它。
#3
0
You can also use to get number from string:
您还可以使用从字符串中获取数字:
'TestingSubject2981'.scan(/\d+/)[0].to_i